Angular.js $http intercept “net::ERR_CONNECTION_RE

2019-02-02 20:17发布

问题:

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.

回答1:

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);
            }
        };
    });
});