2

Folks,

I am using $http.get and $http.post all over my code. I am kind of lost as to how to handle errors that occur during these calls in a global fashion. Currently I have .success(doSomething).error(doSomething) on every call.

I would like to change this and instead simply display the error on top of my page.

I read about using interceptors with myapp.something. But I absolutely do not understand how to implement this.

Kindly assist

1 Answer 1

6

Response interceptors are attached during the config phase of an angularjs app. You can use them to globally respond to any $http request. Be aware, template files also use $http request, so you may wish to filter some requests in your interceptor to only the ones you wish to respond to.

A good understanding of the promises pattern is needed to successfully use response interceptors.

Heres an example of how they are used:

angular.module('services')
    .config(function($httpProvider){
        //Here we're adding our interceptor.
        $httpProvider.responseInterceptors.push('globalInterceptor');
    })
    //Here we define our interceptor
    .factory('globalInterceptor', function($q){
        //When the interceptor runs, it is passed a promise object
        return function(promise){

            //In an interceptor, we return another promise created by the .then function.
            return promise.then(function(response){
                //Do your code here if the response was successful

                //Always be sure to return a response for your application code to react to as well
                return response;
            }, function(response){
                //Do your error handling code here if the response was unsuccessful

                //Be sure to return a reject if you cannot recover from the error somehow.
                //This way, the consumer of the $http request will know its an error as well
                return $q.reject(response);
            });
        }
    });
Sign up to request clarification or add additional context in comments.

1 Comment

ATTENTION!! This method has been deprecated. Follow this link for the alternative, docs.angularjs.org/api/ng.$http

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.