admin管理员组

文章数量:1296314

My $http functions can return the following errors:

POST /foobar 500 (Internal Server Error)

POST /foobar 401 (Unauthorized)

Isn't there a way I can catch all status codes?

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

Where $scope.setTemplate() is a function inside the Controller that sets a view.

But then I have to do this for each error() function and there are a lot functions like this which also not making it DRY code :P

What I want is to catch the error and do an action based on the status code returned in the error.

FYI: I'm not using Angulars $routeProvider().

My $http functions can return the following errors:

POST http://foobar.dev/foobar 500 (Internal Server Error)

POST http://foobar.dev/foobar 401 (Unauthorized)

Isn't there a way I can catch all status codes?

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

Where $scope.setTemplate() is a function inside the Controller that sets a view.

But then I have to do this for each error() function and there are a lot functions like this which also not making it DRY code :P

What I want is to catch the error and do an action based on the status code returned in the error.

FYI: I'm not using Angulars $routeProvider().

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Dec 2, 2015 at 13:25 user1469734user1469734 80114 gold badges52 silver badges94 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You can use the Angular $http interceptor for this like @Dalorzo explained:

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 ment)
                if (status != 422) {
                    var routes = {'401': 'show-login', '500': 'server-error'};
                    $rootScope.$broadcast("ajaxError", {template: routes[status]});
                }

                return $q.reject(response);
            }
        };
    }]);
});

Then receive it in your controller:

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

Now, you don't have to put in your each error function.

How about something like this instead:

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

Where routes is a dictionary with your error codes and desired routing.

This is exactly what $http interceptors are for. See the interceptors section here: $http

Basically, you create mon functionality for all $http requests, in which you can handle different statuses. For example:

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

What I would say initially is to create a decorator for the $http service or create a service that would serve as a wrapper for the $http service.

本文标签: javascriptAngularJS catch all statuscodes for http actionsStack Overflow