0

How to have an $http interceptor to react only to given patterns?

For instance, i would like the interceptor to handle every "/api/*" request and leave the other requests alone.

1
  • 1
    you can't selectively apply an interceptor, so the interceptor will have to evaluate the config object (docs.angularjs.org/api/ng/service/$http#usage) of the request and decide if it should take action or not. Commented Oct 13, 2015 at 16:49

1 Answer 1

1

You can filter the url in success or rejection functions both in the request or response.

Lets say you need to handle the errors for requests and responses for urls which start with "math/".

Here is your interceptor.

$httpProvider.interceptors.push(function($q, mathError) {
                        return {

                            requestError: function(rejection){                            
                                mathError.anyError(rejection);    
                                return $q.reject(rejection);
                            },

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

Here is your factory where you handle it

myApp.factory('mathError', function(){
    return {
                anyError: function(rejection){ 

                     if (rejection.config.url.substr(0, 5) === "math/") {

                         console.log("Only Math errors are handled here"); 

                         //Do whatever you need here
                     }
                }            

});
Sign up to request clarification or add additional context in comments.

Comments

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.