我已经将factory
推进$httpProvider
interceptors
function httpErrorHandler($q) {
return {
'responseError': function (response) {
if (response.status === 500) {
if (response.data && response.data.html) {
var msg = angular.fromJson(response.data.html).Data;
showStatusMessage(msg, 'error'); // assume available
} else {
showStatusMessage(response.statusText, 'error');
}
}
// Always reject (or resolve) the deferred you're given
return $q.reject(response);
}
};
}
和拦截器代码:
function config($httpProvider) {
$httpProvider.interceptors.push('HttpErrorHandler');
}
当我从服务器收到失败的回复时,查看Chrome DevTools>网络选项卡,选择失败的XHR和响应选项卡,我得到:
{"Success":false,"Data":"Error Code 0000-229566."}
状态消息中显示的内容是response.statusText
要尝试完成,请参阅响应标题:
Cache-Control:no-cache, no-store, must-revalidate
Content-Length:110
Content-Security-Policy:frame-ancestors 'self'
Content-Type:application/json; charset=utf-8
Date:Fri, 26 Aug 2016 16:26:11 GMT
Expires:-1
Pragma:no-cache
Strict-Transport-Security:max-age=31536000; includeSubDomains
X-Content-Type-Options:nosniff
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
我想要的是"错误代码000-1234"显示在我的状态信息中,但它没有到来。我怎么能让它出现?
答案 0 :(得分:0)
您正在阅读响应标头的 statusText 属性,而不是访问响应内容的 .Data 属性。 statusText 似乎就是对回复状态代码more here的描述。
编写一份工作样本:https://embed.plnkr.co/xz54Mh2zGguHB0cLquGE/ 我的错误消息属性为 .status_message ,而不是 .Data
responseError: function (response) {
/*
NOTE: if "status_message" is not in the parsing string JSON.parse(response.data.html).status_message
will thrown an undefined error and break the execution
*/
var msg = !response.data ? 'Error occured ...'
: !response.data.html ? response.data.status_message : JSON.parse(response.data.html).status_message;
$alert.show(msg, 'danger');
return $q.reject(response);
}