Javascript AngularJS是否捕获$http操作的所有状态代码?

Javascript AngularJS是否捕获$http操作的所有状态代码?,javascript,angularjs,angular-http,Javascript,Angularjs,Angular Http,My$http函数可能返回以下错误: POST 500(内部服务器错误) 邮政401(未经授权) 难道没有一种方法可以捕捉所有的状态码吗 $http.post('/foobar', form) .success(function(data, status, headers, config) { console.info(data); }) .error(function(data, status, headers, config) { co

My
$http
函数可能返回以下错误:

POST 500(内部服务器错误)

邮政401(未经授权)

难道没有一种方法可以捕捉所有的状态码吗

$http.post('/foobar', form)
    .success(function(data, status, headers, config) {
        console.info(data);
    })
    .error(function(data, status, headers, config) {
        console.error(data);
        if(status === 401) {
            $scope.setTemplate('show-login');
        }
        if(status === 500) {
            $scope.setTemplate('server-error');
        }
    }
);  
其中,
$scope.setTemplate()
是控制器中设置视图的函数

但是我必须对每个
error()
函数都这样做,并且有很多这样的函数也不会使它成为干代码:p

我想要的是捕获错误并根据错误中返回的状态代码执行操作


仅供参考:我没有使用Angulars
$routeProvider()

这样的东西怎么样:

var routes = {'401':'show-login', '500': 'server-error'}; 
$scope.setTemplate(routes[status]);

其中
routes
是一个包含错误代码和所需路由的字典。

这正是
$http
拦截器的用途。请参阅此处的拦截器部分:

基本上,您可以为所有
$http
请求创建通用功能,您可以在其中处理不同的状态。例如:

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2){
    return {
        response: function(response){
            // do something for particular error codes
            if(response.status === 500){
                // do what you want here
            }
            return response;
        }
    };
});

// add the interceptor to the stack
$httpProvider.interceptors.push('myHttpInterceptor');

您可以使用Angular
$http
拦截器执行此操作,如@Dalorzo所述:

var myApp = angular.module("myApp", [], ['$httpProvider', function($httpProvider) {

    $httpProvider.interceptors.push(['$rootScope', '$q', function($rootScope, $q) {
        return {
            'responseError': function(response) {
                var status = response.status;
                // Skip for response with code 422 (as asked in the comment)
                if (status != 422) {
                    var routes = {'401': 'show-login', '500': 'server-error'};
                    $rootScope.$broadcast("ajaxError", {template: routes[status]});
                }

                return $q.reject(response);
            }
        };
    }]);
});
然后在控制器中接收:

$scope.$on("ajaxError", function(e, data) {
    $scope.setTemplate(data.template);
});

现在,您不必输入each
error
函数。

我最初要说的是为
$http
服务创建一个服务,或者创建一个服务作为
$http
服务的包装器。

不,不会让它成为枯燥的代码。然后,我仍然需要将该行添加到每个错误函数中。请解释您在回答问题时遇到的问题,而不是向下投票,因为我认为答案最符合您的需要。@user1469734这比这个简单多少。如果你知道如何分享它,这看起来很棒!除了上面的
$数据("ajaxError
总是未定义抱歉。我的错误。该函数的第一个参数是event。我已经更新了答案,请检查。如果不成功,请告诉我。我会尝试一下。很好!现在有一个问题;它现在总是拒绝错误。我有422个不同的响应。所以我尝试了这个:`` responseError':function(response){if(response.status==422){return response;}//然后是您的代码,但这不是修复方法```