Reputation: 2082
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?
Upvotes: 5
Views: 1817
Reputation: 48972
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);
}
};
});
});
Upvotes: 3
Reputation: 1027
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');
});
Upvotes: 0