gpt4 book ai didi

javascript - $httpProvider.interceptors 的自定义错误消息

转载 作者:行者123 更新时间:2023-12-03 05:00:39 25 4
gpt4 key购买 nike

我们已经实现了以下内容

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,并且response.status中的状态为404

所以现在的消息是

(404) {"detail": "Not found"}

这很丑陋而且没有帮助!

我想提供我自己的定制消息,我该如何实现?

最佳答案

如果我正确理解您的问题,那么您希望从 ErrorInteceptor() 函数返回自定义错误。您会收到同样的错误,因为您正在返回 responsereturn $q.reject(response); 因此,请尝试从您的服务返回自定义消息。

试试这个

 return {
responseError: function(response) {
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.statusText);// this is what you should return
}
};

关于javascript - $httpProvider.interceptors 的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42240165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com