简体   繁体   English

拦截Angular $ http中的服务器错误并拒绝promise

[英]Intercepting server errors in Angular $http and rejecting promise

I'm using the Angular HTTP service and intercepting the response from the server to catch any server errors and do some stuff with them (logging etc.) before rejecting the promise. 我正在使用Angular HTTP服务并拦截来自服务器的响应,以捕获任何服务器错误并在拒绝诺言之前对它们进行一些处理(记录等)。

As an aside, I sometimes get things like validation errors back in the body of the response even though the status code is 200. I know that's not ideal but please don't get hung up on that as it's not the cause of my problem. 顺便说一句,即使状态码为200,有时也会在响应的正文中出现诸如验证错误之类的信息。我知道这并不理想,但请不要挂在嘴上,因为这不是我的问题的根源。 I thought I'd mention it though as it explains why I'm intercepting response and responseError 我以为我提到了它,因为它解释了为什么我拦截了response和responseError

$httpProvider.interceptors.push(function($log, $rootScope, $q) {

    return {
        response: function(response) {

            if (response.data && response.data.success === false) {
                doSomeStuff(response);
                return $q.reject(response);
            }
            else{
                return response;
            }

        },
        responseError: function(rejection) {
            doSomeStuff(rejection);
            $q.reject(rejection);
        }

    };

});

Then, a typical HTTP call in my app might look like this. 然后,我的应用程序中的典型HTTP调用可能如下所示。

$http.post('https://domain.com/api/whatever', data).then(function (response) {
    console.log("Don't do this when an error is returned")
});

Unfortunately, the console.log always runs, even if there is an HTTP error, or a 200 status with embedded errors. 不幸的是,即使出现HTTP错误或状态为200且存在嵌入式错误,console.log始终会运行。

I'm sure I'm just misunderstanding how $http/$q works here and somebody will be able to put me straight. 我敢肯定,我只是误解了$ http / $ q在这里的工作方式,有人可以直截了当。

$q.reject(rejection);

returns a new rejected promise, it doesn't affect the state of existing promise. 返回一个新的被拒绝的诺言,它不会影响现有诺言的状态。 In fact, all that responseError does here is catches the rejection and returns undefined response instead. 实际上, responseError在这里所做的所有事情都是捕获拒绝并返回undefined响应。

It should be 它应该是

    responseError: function(rejection) {
        doSomeStuff(rejection);
        return $q.reject(rejection);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM