39

I'm trying to write a generic error handler for my website using $http's interceptors but they don't seem to be able to do what I want to do.

I placed interceptors on 'response' and 'responseError' but they never get called when the server is offline/not reponding (net::ERR_CONNECTION_REFUSED). I understand why this happens, there's no response to intercept.

I'd like to know if there's a generic way of catching these errors, other than listening to the $httpPromise's error callback for each request.

SBSTP
  • 3,479
  • 6
  • 30
  • 41

1 Answers1

65

You can probably check the status of the ResponseError. When an API is offline that is 0 (until Angular 1.3.18) or -1 (since Angular 1.3.19):

angular.module("services.interceptor", arguments).config(function($httpProvider) {
     $httpProvider.interceptors.push(function($q) {
        return {
          responseError: function(rejection) {
                if(rejection.status <= 0) {
                    window.location = "noresponse.html";
                    return;
                }
                return $q.reject(rejection);
            }
        };
    });
});
dizel3d
  • 3,619
  • 1
  • 22
  • 35
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76
  • Yes that seems to work. I thought I tried listening to `responseError` but clearly, there's something I didn't do right. – SBSTP May 28 '14 at 15:29
  • Is there a way to handle such errors after the "config time" or when the $scope is available? In order to show errors using a controller. Maybe it's the wrong way to show net errors but i can't find a proper way... – fat May 23 '15 at 13:39
  • 3
    Yes, you can inject `$injector` and transit to some state. For example: ``` angular.module('module').factory('accessHttpInterceptor', [ '$injector', function( $injector ) { return { responseError: function accessHttpInterceptorResponseError (rejection) { var $state = $injector.get('$state'); $state.go('offline'); } }; } ]); ``` – Maciej Dzikowicki Oct 20 '15 at 05:38
  • This Answer helped with the $q definition: http://stackoverflow.com/questions/26171986/angularjs-httpprovider-interceptor-documentation – Gary Mar 20 '17 at 14:54