0
votes

I am making a http interceptor in angular and I want to make throw error from response of $httpProvider interceptor.

As per the documentation:

response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

I want to do the bold part in above quote so that a response with status 200 (I've a condition there) is routed to responseError where I will handle the error. Not returning a response throws following error:

Cannot read property 'data' of undefined

I do not want to return the response but want to pass it to next handler i.e responseError.

How can I do that? I hope I made it clear. Thanks.

Update (Code Below):

app.config(['$httpProvider', function($httpProvider) {
    interceptor.$inject = ['$q', '$rootScope'];
    $httpProvider.interceptors.push(interceptor);

    function interceptor($q, $rootScope) {
        return {
            response: response,
            responseError: responseError
        };

        function response(response) {
            if (response.data.rs == "F") {
                // I want to route it responseError -->
            } else {
                return response;
            }
        }

        function responseError(response) {
            // I want to handle that error here
        }
    }

}]);
1
Show your code mate - Satpal
@Satpal pls check - pranavjindal999

1 Answers

2
votes

Use:

return $q.reject(response);

Also make sure you return: (Read about it here)

return response || $q.when(response);

instead of:

return response;