Search code examples
angularjshttpresponseinterceptor

Why is the response with error code (500) treated as successful response while using interceptor


I am trying to use an Angular interceptor for handling my 500 or 403 error codes. For other codes I have custom business implementation. However it seems using interceptor makes Angular treat error responses as success responses and my success callback in .then is called. Isn't this strange, considering docs which says 200-299 codes are only treated as success response.

My code:

function appInterceptorFn(){
        var interceptor = {
            responseError: function (config) {
                if (config && config.status === cramConfig.FORBIDDEN_ACCESS_CODE) {
                    $rootScope.$emit('ERROR_EVENT', config);
                }
                return config;
            }
        }

        return interceptor;
    }

Is there something that can be done to avoid it, I am using AngularJS v1.3.17

I have visited this link which shows a different implementation but I would like to use interceptor preferably.

Is this a known issue ?


Solution

  • by returning your object "normally", you tell angular to treat your error as a success.

    You have to replace your

      return config;
    

    with

      return $q.reject(config);
    

    Explanation

    If you look at the documentation here : https://docs.angularjs.org/api/ng/service/$http#interceptors , you will see the following:

    // optional method
    'responseError': function(rejection) {
       // do something on error
       if (canRecover(rejection)) {
         return responseOrNewPromise
       }
       return $q.reject(rejection);
    }
    

    I know it's not a lot of documentation, but it tells you that if you return an object, or a promise, it will resolve your error as if there was no error. If you want your error to be re-thrown, you have to do it explicitly by using $q.reject()