AngularJS的全局Ajax错误处理程序

时间:2012-08-15 14:30:18

标签: javascript ajax angularjs

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

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

为401错误设置全局处理程序。现在,我使用带有$resource$http的angularjs来向服务器发出我的(REST)请求。有没有办法用angular?

类似地设置一个全局错误处理程序

3 个答案:

答案 0 :(得分:97)

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

"Authentication in AngularJS (or similar) based application." espeo软件

编辑:最终解决方案

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

答案 1 :(得分:77)

请注意,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')

答案 2 :(得分:16)

使用以下内容创建文件<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);
}());