【发布时间】:2017-01-15 07:25:37
【问题描述】:
我正在使用$http 拦截器来捕获 ajax 提交后的所有事件。出于某种原因,我无法抛出requestError。我已经设置了一个测试应用程序来尝试调用requestError,但到目前为止我只能获得多个responseErrors。
来自 angularjs 文档:
requestError:当前一个拦截器抛出错误或被拒绝解决时,拦截器被调用。
这是我的测试代码。
.factory('httpInterceptor',['$q',function(q){
var interceptor = {};
var uniqueId = function uniqueId() {
return new Date().getTime().toString(16) + '.' + (Math.round(Math.random() * 100000)).toString(16);
};
interceptor.request = function(config){
config.id = uniqueId();
console.log('request ',config.id,config);
return config;
};
interceptor.response = function(response){
console.log('response',response);
return response;
};
interceptor.requestError = function(config){
console.log('requestError ',config.id,config);
return q.reject(config);
};
interceptor.responseError = function(response){
console.log('responseError ',response.config.id,response);
return q.reject(response);
};
return interceptor;
}])
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
}])
.controller('MainCtrl',['$http',function($http){
var mainCtrl = this;
mainCtrl.method = null;
mainCtrl.url = null;
var testHttp = function testHttp() {
$http({method:mainCtrl.method,url:mainCtrl.url}).then(
(response)=>{console.log('ok',response);},
(response)=>{console.log('reject',response);}
);
};
//api
mainCtrl.testHttp = testHttp;
}])
我尝试了多种创建 http 错误的方法,但每次只有 responseError 被调用。我尝试过的事情:
- 让服务器为每个请求返回不同类型的错误,例如
400和500。 - 让服务器随机到达
sleep,以便在较早的请求之前获得一些较晚的请求以错误响应。相同的资源,相同的服务器响应。 - 通过请求不存在的资源来生成
404错误。 - 与互联网断开连接 (
responseError -1)。
类似问题
1) 这个问题似乎有答案: When do functions request, requestError, response, responseError get invoked when intercepting HTTP request and response?
关键段落是:
一个关键点是上述任何方法都可以返回一个 “正常”对象/原语或将通过 适当的值。在后一种情况下,下一个拦截器 queue 将等待返回的 promise 被解决或拒绝。
但我认为我正在做它规定的事情,即服务器随机sleep,但没有运气。我从请求中得到了reponseErrors,即服务器响应时出现故障。
2) 大约 1 年前有人问过类似的问题:Angular and Jasmine: How to test requestError / rejection in HTTP interceptor?
很遗憾,它只提供了interceptors 的解释。它没有回答我的问题。
我已经在 Chrome 和 Firefox 中进行了测试。我希望您能理解,我已尽力找到解决方案,但我还没有找到解决方案。
【问题讨论】:
-
您的所有示例都涉及来自服务器的响应 - 或缺少它,因此它是 responseError。顾名思义,requestError 应该处理 client 端的错误,即当
config对象不正确时。 -
@estus 感谢指针。在请求中抛出错误并返回
$q.reject()不起作用。我会尝试下面 rubie_newbie 建议的其他方法。
标签: javascript angularjs angular-http-interceptors