AngularJS捕获$http操作的所有状态代码

AngularJS catch all status-codes for $http actions?

本文关键字:状态 代码 操作 捕获 http AngularJS      更新时间:2023-09-26

我的$http函数可以返回以下错误:

岗位http://foobar.dev/foobar500(内部服务器错误)

岗位http://foobar.dev/foobar401(未经授权)

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

$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()函数做这件事,有很多类似的函数也不能使其成为DRY代码:p

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

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

您可以使用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);
});

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

不如这样做:

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

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

这正是$http拦截器的用途。请参阅此处的拦截器部分:$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');

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