Intercepting server errors in Angular $http and re

2019-09-05 07:39发布

问题:

I'm using the Angular HTTP service and intercepting the response from the server to catch any server errors and do some stuff with them (logging etc.) before rejecting the promise.

As an aside, I sometimes get things like validation errors back in the body of the response even though the status code is 200. I know that's not ideal but please don't get hung up on that as it's not the cause of my problem. I thought I'd mention it though as it explains why I'm intercepting response and responseError

$httpProvider.interceptors.push(function($log, $rootScope, $q) {

    return {
        response: function(response) {

            if (response.data && response.data.success === false) {
                doSomeStuff(response);
                return $q.reject(response);
            }
            else{
                return response;
            }

        },
        responseError: function(rejection) {
            doSomeStuff(rejection);
            $q.reject(rejection);
        }

    };

});

Then, a typical HTTP call in my app might look like this.

$http.post('https://domain.com/api/whatever', data).then(function (response) {
    console.log("Don't do this when an error is returned")
});

Unfortunately, the console.log always runs, even if there is an HTTP error, or a 200 status with embedded errors.

I'm sure I'm just misunderstanding how $http/$q works here and somebody will be able to put me straight.

回答1:

$q.reject(rejection);

returns a new rejected promise, it doesn't affect the state of existing promise. In fact, all that responseError does here is catches the rejection and returns undefined response instead.

It should be

    responseError: function(rejection) {
        doSomeStuff(rejection);
        return $q.reject(rejection);
    }