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

使用axios拦截器处理401后外层try/catch无法获取AxiosError实例怎么办

问题根因

axios响应拦截器的错误处理分支如果没有显式抛出错误,错误会被拦截器直接消化,后续的Promise链路会变为成功状态,外部的try/catch自然无法捕获到AxiosError实例,只会拿到undefined或者完全不进入catch分支。

修复方案

修改拦截器逻辑,在处理完401登出逻辑后,返回Promise.reject(error)将错误继续向下传递:

api.interceptors.response.use( 
  (response: AxiosResponse) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      signOut();
    }
    // 核心逻辑:抛出错误,传递到外部调用链路
    return Promise.reject(error);
  },
);
可选优化

外部try/catch块中建议先做类型校验,避免非AxiosError类型的异常导致属性读取报错:

import axios from 'axios'

try {
  // 你的axios请求逻辑,必须加await才能被try/catch捕获异步错误
  await api.get('/your/request/path')
} catch (err) {
  if (axios.isAxiosError(err)) {
    console.log(err.response?.status);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:24:03