Home > Mobile >  Axios response interceptor - get API response for non 2xx http statuses
Axios response interceptor - get API response for non 2xx http statuses

Time:11-30

I have a custom Axios instance that uses interceptors to return responses. According to the Axios docs, the success interceptor is called whenever there is a 2xx status and the error interceptor is called if it's any status other than 2xx. I want to display an error dialog when the error interceptor is called.

The problem: I want to display the error message coming from the API response in the dialog. For instance, the API may respond with 401 status and still have a custom response with user friendly error messages. However, I am not sure how to obtain the response in the error interceptor function itself.

const responseErrorInterceptor = async (error: AxiosError): ServiceResult<AxiosError> => {
  if (error.response) {
    store.dispatch(setErrorDialog(undefined, /*display api error response here*/));
    //right now it just displays the unfriendly Axios error content
  }
  return Promise.reject(error);
};

Any ideas if it's possible to achieve this?

CodePudding user response:

Yes, it is possible to achieve this. The AxiosError object passed to the error interceptor function contains a response property which contains the response data from the API. You can use this to get the user friendly error message and display it in the dialog.

For example:

const responseErrorInterceptor = async (error: AxiosError): ServiceResult<AxiosError> => {
  if (error.response) {
    const userFriendlyErrorMessage = error.response.data.errorMessage;
    store.dispatch(setErrorDialog(undefined, userFriendlyErrorMessage));
  }
  return Promise.reject(error);
};
  • Related