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

TypeScript try/catch块中Error类型不存在response属性问题求助

解决TypeScript中Axios错误处理的response属性不存在问题

问题出在你用原生Error类型判断Axios抛出的错误——Axios实际抛出的是它自己封装的AxiosError类型,原生Error并没有response属性,所以TS会报错。

下面是两种靠谱的解决方式:

方式一:使用Axios自带的类型守卫(推荐)

先导入AxiosError类型,然后用instanceof判断,TS就能正确识别类型并提供语法提示:

import { AxiosError } from 'axios';

// 把await和then混用的写法改成纯await,逻辑更清晰
try {
  const res = await axios_auth.put(`${"http://localhost:4500/api" + API_CALL}`, values);
  console.log(res.data.success);
} catch (err: any) {
  // 判断是否是Axios封装的错误
  if (err instanceof AxiosError) {
    // 用可选链?.避免response不存在的情况(比如网络错误导致请求未到达服务器)
    if (err.response?.status === 400 && err.response.data.code === "CATEGORY_ALREADY_EXIST") {
      console.log("Category exists");
    }
  } else {
    console.log('Unexpected error', err);
  }
}

方式二:类型断言(快速解决,适合临时场景)

如果不想导入类型,可以用类型断言告诉TS这个错误是AxiosError类型,但这种方式没有实际类型检查,安全性不如类型守卫:

try {
  const res = await axios_auth.put(`${"http://localhost:4500/api" + API_CALL}`, values);
  console.log(res.data.success);
} catch (err: any) {
  const axiosErr = err as import('axios').AxiosError;
  if (axiosErr.response?.status === 400 && axiosErr.response.data.code === "CATEGORY_ALREADY_EXIST") {
    console.log("Category exists");
  } else {
    console.log('Unexpected error', err);
  }
}

额外提醒

  • 必须用可选链?.访问err.response,否则当请求未到达服务器(如网络中断)时,直接访问会触发运行时错误。
  • 尽量避免await和then混用,保持代码风格一致,可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 02:05:32