如何使用axios请求拦截器捕获网络错误?

问题描述 投票:0回答:2

我们的 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;
  });
});
javascript vue.js axios
2个回答
1
投票

你尝试过吗?

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);
  });

参考:https://axios-http.com/docs/interceptors


0
投票

代码示例不起作用的原因是它是一个请求拦截器,将在发送请求之前运行。要捕获网络错误,请使用响应拦截器。

axiosInstance.interceptors.response.use(
  (response) => response,
  (error: Error | AxiosError) => {
    if (error instanceof CanceledError || error.message === 'Network Error') {
      // Handle timeout (CanceledError) or offline (Network Error) here
    }
  });

此外,无需重新抛出错误。稍后的 Catch 块仍然会收到错误

© www.soinside.com 2019 - 2024. All rights reserved.