I am struggling to understand when $q/$http should trigger the onReject
block.
For example, if I have a simple call like this:
$http.get('/users')
.then(function(res) {
return res.data;
}, function(err) {
console.log(err);
});
If I encounter a 500 Internal Server Error
, it ends up in the onSuccess
block. It seems strange to me because technically I did receive a response? My understanding of promises tells me that this is correct, but having error handling logic in an onSuccess
block doesn't feel right.
if(res.status >= 400) {
return $q.reject('something went wrong: ' + res.status);
}
Should I handle 400+ status codes in the onSuccess
block or should I return a rejected promise to ensure the onReject
block is executed? Is there a better way to handle this situation that I am missing?
I attempted to handle this in an httpInterceptor
, but I was unable to figure out how to return a rejected promise from there.
this.responseError = function(res) {
if(res.status >= 400) {
// do something
}
return res;
};