- Azure
Black Sand Solutions
$http Service Not Calling Error Callback on 400
- AngularJS
I came across a wee little problem with Angular that had me stumped for a while today.
$http Service Not Calling Error Callback on 400
I was trying to add some error handling to a $http.post call made from within a service.
function postToServer() {
return $http.post(APP_CONFIG.apiBaseUrl + 'doSomething', service.data)
.then(
function (response) {
// all good
return response;
},
function (response) {
// oh no, dragons!
return response;
}
);
I've done this a gazillion times, but for some reason, despite the server returning a 400, the error callback was never hit.
Adding a breakpoint into the dev console I could see that the response coming back from the server was as expected; but the angular success callback was always called.
I played around with a few things:
- using the legacy 'success' and 'error' instead of 'then'
- using a 'catch'
But still, no dice.
Alas, a little Goolgling had me heading in the right direction.
I was using some custom $http interceptors, one for Auth and one to start and stop a loading spinner. The problem was with the later.
It turns out that you need to manually reject any promises in methods that handle response or request errors.
E.g. Dont do this
function responseError(response) {
usSpinnerService.stop('spinner-main');
return response;
}
But this
function responseError(response) {
usSpinnerService.stop('spinner-main');
return $q.reject(response);
}
This ensures that the correct callback is handled further down the promise chain.