Javascript 使用 AngularJS 的全局 Ajax 错误处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11971213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:53:10  来源:igfitidea点击:

Global Ajax error handler with AngularJS

javascriptajaxangularjs

提问by cricardol

When my website was 100% jQuery, I used to do this:

当我的网站是 100% jQuery 时,我曾经这样做:

$.ajaxSetup({
    global: true,
    error: function(xhr, status, err) {
        if (xhr.status == 401) {
           window.location = "./index.html";
        }
    }
});

to set a global handler for 401 errors. Now, I use angularjs with $resourceand $httpto do my (REST) requests to the server. Is there any way to similarly set a global error handler with angular?

为 401 错误设置全局处理程序。现在,我使用 angularjs$resource$http向服务器发出我的(REST)请求。有什么方法可以类似地设置带有角度的全局错误处理程序?

回答by Justen

I'm also building a website with angular and I came across this same obstacle for global 401 handling. I ended up using http interceptor when I came across this blog post. Maybe you'll find it as helpful as I did.

我也在用 angular 构建一个网站,我遇到了同样的全局 401 处理障碍。当我看到这篇博文时,我最终使用了 http 拦截器。也许你会发现它和我一样有用。

"Authentication in AngularJS (or similar) based application.", espeo software

“基于 AngularJS(或类似)的应用程序中的身份验证。” , espeo 软件

EDIT: final solution

编辑:最终解决方案

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {

    var interceptor = ['$rootScope', '$q', function (scope, $q) {

        function success(response) {
            return response;
        }

        function error(response) {
            var status = response.status;

            if (status == 401) {
                window.location = "./index.html";
                return;
            }
            // otherwise
            return $q.reject(response);

        }

        return function (promise) {
            return promise.then(success, error);
        }

    }];
    $httpProvider.responseInterceptors.push(interceptor);

回答by MikeR

Please note that responseInterceptors have been deprecated with Angular 1.1.4. Below you can find an excerpt based on the official docs, showing the new way to implement interceptors.

请注意 responseInterceptors 已被 Angular 1.1.4 弃用。您可以在下面找到基于官方文档的摘录,展示了实现拦截器的新方法。

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
      // do something on success
      return response || $q.when(response);
    },

   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise;
      }
      return $q.reject(rejection);
    }
  };
});

$httpProvider.interceptors.push('myHttpInterceptor');

This is how it looks in my project using Coffeescript:

这是它在我的项目中使用 Coffeescript 的样子:

angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
  response: (response) ->
    $log.debug "success with status #{response.status}"
    response || $q.when response

  responseError: (rejection) ->
    $log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
    switch rejection.status
      when 403
        growl.addErrorMessage "You don't have the right to do this"
      when 0
        growl.addErrorMessage "No connection, internet is down?"
      else
        growl.addErrorMessage "#{rejection.data['message']}"

    # do something on error
    $q.reject rejection

.config ($provide, $httpProvider) ->
  $httpProvider.interceptors.push('myHttpInterceptor')

回答by Jan-Terje S?rensen

Create the file <script type="text/javascript" src="../js/config/httpInterceptor.js" ></script>with this content:

<script type="text/javascript" src="../js/config/httpInterceptor.js" ></script>使用以下内容创建文件:

(function(){
  var httpInterceptor = function ($provide, $httpProvider) {
    $provide.factory('httpInterceptor', function ($q) {
      return {
        response: function (response) {
          return response || $q.when(response);
        },
        responseError: function (rejection) {
          if(rejection.status === 401) {
            // you are not autorized
          }
          return $q.reject(rejection);
        }
      };
    });
    $httpProvider.interceptors.push('httpInterceptor');
  };
  angular.module("myModule").config(httpInterceptor);
}());