Home > Back-end >  How to catch network errors with Axios request interceptor?
How to catch network errors with Axios request interceptor?

Time:02-19

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

CodePudding user response:

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.com/docs/interceptors

  • Related