[英]Accessing Axios error codes in interceptor
When using axios response interceptors in client-side JavaScript/React/etc, how can I access error codes such as the following:在客户端 JavaScript/React/etc 中使用axios响应拦截器时,如何访问如下错误代码:
ERR_CONNECTION_REFUSED
(API server is down) ERR_CONNECTION_REFUSED
(API 服务器已关闭)ERR_INTERNET_DISCONNECTED
(local network is down) ERR_INTERNET_DISCONNECTED
(本地网络已关闭) I noticed that these codes get printed to the console by axios/lib/adapters/xhr.js
, but I can't seem to work out how to access them myself in my response interceptor?我注意到这些代码通过
axios/lib/adapters/xhr.js
打印到控制台,但我似乎无法在我的响应拦截器中自己访问它们?
Code:代码:
axios.interceptors.response.use(null, (error) => {
console.log(error.???);
return Promise.reject(error);
}
NB: The point is to be able to distinguish between "Your internet is down" and "Our API is down" when showing an error message to the user.注意:关键是在向用户显示错误消息时能够区分“您的互联网已关闭”和“我们的 API 已关闭”。
You can get status like this error.response.status
but write safe code since it is not always true.您可以像这样
error.response.status
获得状态,但编写安全代码,因为它并不总是正确的。 In case of 502, error.response is undefined and will break在 502 的情况下,error.response 未定义并且会中断
Here is how you can handle your errors这是您如何处理错误的方法
axios.interceptors.response.use(null, (error) => { if (error.message === 'Network Error') { if (error?.response?.status') === 504) { throw { message: 'Something went wrong. Please try again later.', }; } else { throw { message: 'You are not connected to the internet. Verify your connection and then try again.', }; } } if (error.response) { if (error.response.status === 500) { throw { message: 'Something went wrong. Please try again later.', }; } if (error.response.status === 401) { // logout logic } if (error.response.status === 403) { // redirect user to some home page since that action is not allowed } throw {...error.response.data, statusCode: error.response.status }; } throw { message: 'Something went wrong. Please try again later.', }; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.