所以我有一个服务定义如下:
angular.module('services', ['ngResource'])
.factory('Things', function ($rootScope, $http) {
var basePath = 'rest/things/';
return {
getAll: function () {
return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {});
}
};
});
然后,在其他地方,我使用该服务:
Things.getAll().success(function(things){
//do something w/ things
})
.error(function(err){
// Clearly, something went wrong w/ the request
});
我想做的是能够“抛出”错误条件,例如,如果服务级别的数据出现问题。即:
数据返回为:
{
status:500,
message:'There was a problem w/ the data for this client'
}
那么在服务中就会有这样的内容:
getAll: function () {
return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {})
.throwError(function(data){
return (data.status && data.status == 200);
});
}
因此,当 throwError 回调返回 false 时,将调用 error() promise 而不是 success promise 。
有人对如何实现这一目标有任何想法吗?
非常感谢!
最佳答案
如果您确定所有请求都遵循从响应返回的数据包含状态代码的约定,那么使用 HTTP 拦截器是有意义的。为此,您可以创建一个服务并将其推送到 $httpProvider
的拦截器列表:
.factory("myHttpInterceptor", function ($q) {
return {
response: function (response) {
if (response.data.status && (response.data.status === 500)) {
return $q.reject(response);
}
return response || $q.when(response);
}
};
});
您可以将 === 500
替换为 >= 400
之类的内容来处理所有错误,而不仅仅是 500。
并在模块的 .config()
中添加以下内容:
$httpProvider.interceptors.push("myHttpInterceptor");
引用文献:
$http
拦截器:description
关于javascript - 触发 AngularJS $http promise 的错误条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634015/