0
自定義錯誤消息,我們已經實現了以下
function Inteceptors($httpProvider) {
'ng-inject';
$httpProvider.interceptors.push('ErrorInterceptor');
$httpProvider.interceptors.push('LoadingInterceptor');
}
function ErrorInteceptor($q, MyNotificationService) {
'ng-inject';
return {
responseError: function(response) {
var msg = JSON.stringify(response.data);
var status = response.status;
console.log('in ErrorInterceptor', response);
if (response.status === -1) {
status = null;
msg = 'An unspecified error occured while trying to make a request'
}
var notification = {
type: 'error',
status: status,
msg: msg
};
MyNotificationService.add(notification);
return $q.reject(response);
}
};
}
這讓像404和500的錯誤被截獲和消息被提示給用戶。
但是,在某些情況下,我想使用我自己的自定義錯誤消息。
例如,當我有一個函數,使一個呼叫到一個API:
this.list = function() {
return $http({
method: 'GET',
url: myendpoint
})
.then(function(response) {
return response.data;
},
function(err) {
return [];
});
}
的響應看起來像下面在404的情況下:
- Object
-- config: Object
- data: Object
- headers: (name)
- status: 404
- statusText: "Not Found"
- __proto__: Object
所以如果API返回404 ,現在攔截器顯示的response.data是「未找到」,狀態是404響應。狀態
所以現在的消息是
(404) {"detail": "Not found"}
而這是醜陋的,沒有幫助!
我想提供我自己定製的消息,我該如何實現?
哎@sourabh,謝謝。我有其他函數調用API,例如,它會返回一些其他的500錯誤,所以它們是不同的消息,我想ErrorInteceptor()來處理,但是當發生錯誤時,在某些調用API時,我想提供我自己的自定義消息。 –
那麼你是否從服務器返回錯誤? –
是的,服務器返回錯誤。 –