I can't seem to wrap my head around when $q/$http should trigger the onReject
block.
Let's say I have a basic call:
$http.get('/users')
.then(function(res) {
return res.data;
}, function(err) {
console.log(err);
});
If I get a 500 Internal Server Error
I'm going to end up in the onSuccess
block. From my meager understanding of promises I guess this seems correct because I technically did get a response? The problem is an onSuccess
block seems like the wrong place to have a bunch of
if(res.status >= 400) {
return $q.reject('something went wrong: ' + res.status);
}
Just so that my onReject
block will get run. Is this the way it's supposed to work? Do most people handle 400+ statuses in the onSuccess
block or do they return a rejected promise to force the onReject
block? Am I missing a better way to handle this?
I tried doing this in an httpInterceptor
but I couldn't find a way to return a rejected promise from here.
this.responseError = function(res) {
if(res.status >= 400) {
// do something
}
return res;
};
Your success-block will not be hit. Try this and see that error-block will hit if error code > 300.
$http.get('/users').success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});