You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Axios响应错误拦截器中获取非2xx状态的API响应?

可以实现该需求,具体方案如下

当Axios错误拦截器触发时,error.response 对象包含了服务器返回的完整响应信息,其中的 error.response.data 就是API返回的自定义响应内容(包括401这类状态码下的友好提示)。

你可以直接从这个属性中提取需要展示的错误信息,修改后的代码示例如下:

const responseErrorInterceptor = async (error: AxiosError): ServiceResult<AxiosError> => {
  if (error.response) {
    // 假设后端返回的自定义错误信息在 data 的 message 字段中,可根据实际结构调整
    const friendlyErrorMessage = error.response.data?.message || '请求失败,请稍后重试';
    store.dispatch(setErrorDialog(undefined, friendlyErrorMessage));
  }
  return Promise.reject(error);
};

补充说明

  • 不同后端返回的响应结构可能不同,你需要根据实际接口的返回格式调整提取逻辑,比如有的后端会把错误信息放在 errorMsg、msg 等字段中
  • 如果需要针对特定状态码做特殊处理(比如401跳转登录页),可以增加状态码判断:
    if (error.response.status === 401) {
      const authErrorMsg = error.response.data?.message || '登录状态已过期,请重新登录';
      store.dispatch(setErrorDialog(undefined, authErrorMsg));
      // 这里可以添加跳转登录页的逻辑
    } else {
      const otherErrorMsg = error.response.data?.message || '请求失败,请稍后重试';
      store.dispatch(setErrorDialog(undefined, otherErrorMsg));
    }
    

内容的提问来源于stack exchange,提问作者Sean

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:30:49