tputkonen
tputkonen

Reputation: 5729

How to catch network errors with Axios request interceptor?

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

Upvotes: 5

Views: 12213

Answers (2)

Stian Jørgensrud
Stian Jørgensrud

Reputation: 1022

The reason the code example doesn't work is because it is a request interceptor which will run before a request is sent. To catch network errors use a response interceptor.

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
      // For example: throw CustomError
    }
  });

The above code should probably reside in its own file outside of a UI component. In your UI framework (Vue) code one should catch CustomError and show UI.

try {
  axiosInstance.get('/some-path')
} catch (error: Error) {
  if (error instanceof CustomError) {
    // show UI
  }
}

Upvotes: -1

buithienquyet
buithienquyet

Reputation: 354

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

Upvotes: 1

Related Questions