简体   繁体   English

Axios 响应拦截器 - 获取非 2xx http 状态的 API 响应

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

I have a custom Axios instance that uses interceptors to return responses.我有一个自定义的 Axios 实例,它使用拦截器返回响应。 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.根据 Axios 文档,只要有 2xx 状态,就会调用成功拦截器,如果是 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.问题:我想在对话框中显示来自 API 响应的错误消息。 For instance, the API may respond with 401 status and still have a custom response with user friendly error messages.例如,API 可能会以 401 状态响应,并且仍然具有带有用户友好错误消息的自定义响应。 However, I am not sure how to obtain the response in the error interceptor function itself.但是,我不确定如何在错误拦截器 function 本身中获取响应。

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.传递给错误拦截器 function 的 AxiosError object 包含一个响应属性,该属性包含来自 API 的响应数据。您可以使用它来获取用户友好的错误消息并将其显示在对话框中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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