5

I have been looking for a way of managing the http errors that I can have in my angular application. I have been capturing them separately, but I would like to manage them globally. I am using $resource and $http for my http calls. Are there any way of managing them globally?

2 Answers 2

3

Try $http interceptor:

Quoted from the docs:

angular.module('app',[]).config(function($httpProvider){

    $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
      return {
       'request': function(config) {
           return config;
        },

       'response': function(response) {
           // do something on success
           return response || $q.when(response);
        },
        'responseError': function(rejection) {
         // do something on error

           return $q.reject(rejection);
         }
      };
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can capture global errors:

angular.module('app').factory('Interceptor',function($q) {

    'use strict';


    function success(response) {

      return response;
    }

    function error(response) {

      if (response.status === 401) {
        var deferred = $q.defer();
        // here you can broadcast or do anything you want 
        return deferred.promise;
      }
      // otherwise
      return $q.reject(response);
    }

    return function (promise) {

       return promise.then(success, error);
    };
});



angular.module('app').config(function($urlRouterProvider, $locationProvider, $stateProvider, $httpProvider) {
    $httpProvider.responseInterceptors.push('Interceptor');
});

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.