首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用AngularJS的全局Ajax错误处理程序

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

Stack Overflow用户
提问于 2012-08-15 22:30:18
回答 2查看 66.8K关注 0票数 82

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

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

为401个错误设置全局处理程序。现在,我将angularjs与$resource$http一起使用来完成对服务器的(REST)请求。有没有办法以类似的方式用angular设置全局错误处理程序?

EN

回答 2

Stack Overflow用户

发布于 2013-09-12 20:50:04

请注意,在Angular 1.1.4中,responseInterceptors已被弃用。下面你可以找到一个基于official docs的摘录,展示了实现拦截器的新方法。

$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');

这是使用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')
票数 77
EN

Stack Overflow用户

发布于 2014-06-20 14:42:39

使用以下内容创建文件<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);
}());
票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11971213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档