我刚刚在angularJS中构建了一个拦截器服务来捕获API调用中的所有错误,以处理一般错误,如下所示:
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'responseError': function(rejection) {
alert("Something went wrong");
return $q.reject(rejection);
}
};
});
完美地工作,我的服务器发送错误,状态为409
{
message: "Email is already being used"
success: false
token: ""
}
如何从responseError
拦截器访问此响应?
答案 0 :(得分:2)
可以这样做
$httpProvider.interceptors.push(['$q', function($q) {
return {
'request': function (config) {
//request codes
return config;
},
'responseError': function(response) {
console.log(response);
if(response.statusText){
alert(response.statusText)
}else{
alert("Server down")
}
if(response.status === 401 || response.status === 409) {
//response code
}
return $q.reject(response);
}
};
}]);
})
答案 1 :(得分:1)
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'responseError': function(rejection) {
if(rejection.status === 409) {
//get set the error message from rejection.message/rejection.data.message and do what you want
}
alert("Something went wrong");
return $q.reject(rejection);
}
};
});