javascript - How to catch network errors with Axios request interceptor? - Stack Overflow

Our Vue application had some problems and I noticed in Sentry logs that probably the network has been u

Our Vue application had some problems and I noticed in Sentry logs that probably the network has been unreliable:

Error: Network Error
Error: Request aborted

I would like to show warning to the user, but couldn't figure out how to do it. I tried to catch these errors using Axios request interceptor, but they didn't work. Has anyone acplished this?

EDIT:

This is the interceptor that didn't work. I also have a response interceptor to catch 403 and it works perfectly.

axios.interceptors.request.use(undefined, (err) => {
  // Never gets here for network errors
  return new Promise((resolve, reject) => {
    throw err;
  });
});

Our Vue application had some problems and I noticed in Sentry logs that probably the network has been unreliable:

Error: Network Error
Error: Request aborted

I would like to show warning to the user, but couldn't figure out how to do it. I tried to catch these errors using Axios request interceptor, but they didn't work. Has anyone acplished this?

EDIT:

This is the interceptor that didn't work. I also have a response interceptor to catch 403 and it works perfectly.

axios.interceptors.request.use(undefined, (err) => {
  // Never gets here for network errors
  return new Promise((resolve, reject) => {
    throw err;
  });
});
Share Improve this question edited Feb 18, 2022 at 10:11 tputkonen asked Feb 18, 2022 at 9:18 tputkonentputkonen 5,74918 gold badges66 silver badges91 bronze badges 3
  • What exactly did you try? – Estus Flask Commented Feb 18, 2022 at 9:43
  • @EstusFlask I edited the question with a sample code. – tputkonen Commented Feb 18, 2022 at 10:11
  • 2 Why is it request interceptor? You need to handle a response. If you handle Axios errors consistently, you won't get unhandled errors. Network error is detected like !error.status && error.message === 'Network Error'. – Estus Flask Commented Feb 18, 2022 at 10:29
Add a ment  | 

1 Answer 1

Reset to default 1

Did you try?

return Promise.reject(error);

like this:

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

reference: https://axios-http./docs/interceptors

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745152354a4613924.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信