1

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?

1 Answer 1

2

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);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.