Angular.js $ http拦截"net :: ERR_CONNECTION_REFUSED"

SBS*_*STP 38 javascript http interceptor angularjs

我正在尝试使用$http's拦截器为我的网站编写一个通用的错误处理程序,但它们似乎无法做我想做的事情.

我放置了拦截器'response','responseError'但是当服务器脱机/没有响应时它们永远不会被调用(net :: ERR_CONNECTION_REFUSED).我理解为什么会这样,对拦截没有反应.

我想知道是否有一种捕获这些错误的通用方法,除了监听每个请求$httpPromiseerror回调.

Ali*_*deh 65

您可以检查ResponseError的状态.当API脱机时为0(直到Angular 1.3.18)或-1(自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);
            }
        };
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,你可以注入`$ injector`并转移到某个州.例如:```angular.module('module').factory('accessHttpInterceptor',['$ injector',function($ injector){return {responseError:function accessHttpInterceptorResponseError(rejection){var $ state = $ injector. get('$ state'); $ state.go('offline');}};}]); ``` (3认同)