简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM