如何使用 Axios 请求拦截器捕获网络错误?
How to catch network errors with Axios request interceptor?
我们的 Vue 应用程序有一些问题,我在 Sentry 日志中注意到可能是网络不可靠:
Error: Network Error
Error: Request aborted
我想向用户显示警告,但不知道该怎么做。我尝试使用 Axios 请求拦截器捕获这些错误,但它们没有用。有人做到了吗?
编辑:
这是不起作用的拦截器。我还有一个响应拦截器来捕获 403,它工作得很好。
axios.interceptors.request.use(undefined, (err) => {
// Never gets here for network errors
return new Promise((resolve, reject) => {
throw err;
});
});
你尝试了吗?
return Promise.reject(error);
像这样:
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
我们的 Vue 应用程序有一些问题,我在 Sentry 日志中注意到可能是网络不可靠:
Error: Network Error
Error: Request aborted
我想向用户显示警告,但不知道该怎么做。我尝试使用 Axios 请求拦截器捕获这些错误,但它们没有用。有人做到了吗?
编辑:
这是不起作用的拦截器。我还有一个响应拦截器来捕获 403,它工作得很好。
axios.interceptors.request.use(undefined, (err) => {
// Never gets here for network errors
return new Promise((resolve, reject) => {
throw err;
});
});
你尝试了吗?
return Promise.reject(error);
像这样:
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});