0

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 Answer 1

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I can't believe I missed that. I was already doing that in the response section but not in responseError for some reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.