【问题标题】:Angular.js $http intercept "net::ERR_CONNECTION_REFUSED"Angularjs $http 拦截器“net::ERR_CONNECTION_REFUSED”
【发布时间】:2014-05-28 14:48:30
【问题描述】:

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

我在'response''responseError' 上放置了拦截器,但是当服务器离线/无响应时它们永远不会被调用(net::ERR_CONNECTION_REFUSED)。我明白为什么会发生这种情况,拦截没有响应。

我想知道是否有一种通用的方法来捕获这些错误,而不是为每个请求收听$httpPromiseerror 回调。

【问题讨论】:

    标签: javascript angularjs http interceptor


    【解决方案1】:

    您可能可以检查 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);
                }
            };
        });
    });
    

    【讨论】:

    • 是的,这似乎有效。我以为我试过听responseError,但很明显,我做的不对。
    • 有没有办法在“配置时间”之后或 $scope 可用时处理此类错误?为了使用控制器显示错误。也许这是显示网络错误的错误方式,但我找不到正确的方式......
    • 是的,您可以注入$injector 并转换到某个状态。例如:``` angular.module('module').factory('accessHttpInterceptor', [ '$injector', function( $injector ) { return { responseError: function accessHttpInterceptorResponseError (rejection) { var $state = $injector. get('$state'); $state.go('offline'); } }; } ]); ```
    • 这个答案有助于 $q 定义:stackoverflow.com/questions/26171986/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 2023-03-13
    • 2014-06-07
    • 1970-01-01
    相关资源
    最近更新 更多