AngularJS: Catch all response status 500

前端 未结 3 1533
灰色年华
灰色年华 2020-12-31 05:54

This may seem like a strange request. I was wondering if there is a way using a $http interceptor to catch the first URL that has a response status of 500, then stop all sub

3条回答
  •  無奈伤痛
    2020-12-31 06:01

    You can catch all responses through $httpProvider.responseInterceptors.

    To do this you have to create a factory like this:

    app.factory('SecurityHttpInterceptor', function($q) {
            return function (promise) {
                return promise.then(function (response) {
                    return response;
                },
                function (response) {
                    if (response.status === 500) {
                        //DO WHAT YOU WANT
                    }
                    return $q.reject(response);
                });
            };
        });
    

    In this factory you'll catch the response status if it's 500 do what you want. Then reject the response.

    Now you have to put the factory in the responseInterceptors of $httProvider in your config module like that :

    app.config(function ($routeProvider, $httpProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/home.html',
                controller: 'HomeCtrl'
            })
            .otherwise({
                templateUrl: 'views/404.html'
            });
    
        $httpProvider.responseInterceptors.push('SecurityHttpInterceptor');
    })
    

提交回复
热议问题