AngularJS: Catch all response status 500

前端 未结 3 1436
灰色年华
灰色年华 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:02

    Thomas answer is correct, but this solution is currently deprecated. You should do something like this answer.

    app.factory('errorInterceptor', function ($q) {
    
        var preventFurtherRequests = false;
    
        return {
            request: function (config) {
    
                if (preventFurtherRequests) {
                    return;
                }
    
                return config || $q.when(config);
            },
            requestError: function(request){
                return $q.reject(request);
            },
            response: function (response) {
                return response || $q.when(response);
            },
            responseError: function (response) {
                if (response && response.status === 401) {
                    // log
                }
                if (response && response.status === 500) {
                    preventFurtherRequests = true;
                }
    
                return $q.reject(response);
            }
        };
    });
    
    app.config(function ($httpProvider) {
        $httpProvider.interceptors.push('errorInterceptor');    
    });
    

提交回复
热议问题