【发布时间】:2016-03-31 22:39:39
【问题描述】:
我正在使用 Angular HTTP 服务并拦截来自服务器的响应以捕获任何服务器错误并在拒绝承诺之前对其进行一些处理(记录等)。
顺便说一句,即使状态码是 200,我有时也会在响应正文中返回验证错误之类的内容。我知道这并不理想,但请不要挂断电话,因为这不是导致我的问题。我想我会提到它,因为它解释了为什么我要拦截 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);
}
};
});
然后,我的应用程序中的典型 HTTP 调用可能如下所示。
$http.post('https://domain.com/api/whatever', data).then(function (response) {
console.log("Don't do this when an error is returned")
});
不幸的是,console.log 始终运行,即使存在 HTTP 错误,或带有嵌入错误的 200 状态。
我确定我只是误解了 $http/$q 在这里的工作原理,有人可以让我直截了当。
【问题讨论】:
标签: javascript angularjs promise