1

I am searching a way to handle network related errors for my all ngResource based services in one place.

From this answer I know that I can define a custom interceptor for all actions in a single resource. Is it possible to modify default actions that are created by angularjs and pass a custom interceptor there?

Community
  • 1
  • 1
Lukasz
  • 185
  • 1
  • 10
  • You could always create a wrapper service for `$resource` that adds the interceptor. – Phil Sep 30 '15 at 08:30

2 Answers2

1

Here is my solution:

angular.module('server-error', [])
.factory('ErrorResponseInterceptor', function($rootScope, $q) {
    return {
        responseError: function(rejection) {
            var message = null;
            switch (rejection.status) {
                case 0:
                    message = "Unknown network error when loading " + rejection.config.url;
                    break;
                default:
                    message = rejection.status + " " + rejection.statusText + " when loading " + rejection.config.url; 
            }
            $rootScope.$broadcast('event:error-serverError', message);
            return $q.reject(rejection);
        }
    };
})
//for $http
.config(function($httpProvider) {
    $httpProvider.interceptors.push('ErrorResponseInterceptor')
})
//and for ngResource actions
.config(function($resourceProvider) {
    var default_actions = $resourceProvider.defaults.actions;
    angular.forEach(default_actions, function(action) {
        action['interceptor'] = {
                responseError: 'ErrorResponseInterceptor'
        }
    })
})
Lukasz
  • 185
  • 1
  • 10
0

You can set up interceptors on the $http provider, as is documented here (in the section "Interceptors").