如何在catch子句中访问Axios错误响应对象,解决TypeScript类型报错?
问题原因
- TypeScript 4.4及以上版本默认开启了
useUnknownInCatchVariables配置,catch子句捕获的错误对象默认类型为unknown,不允许直接访问任意属性 - Axios 0.23.0之后的类型定义更加严格,没有默认对错误对象做类型兜底,因此直接访问
err.response.status会触发类型报错
解决方法
方案1:使用Axios自带的类型守卫(最推荐)
Axios内置了isAxiosError类型谓词方法,可以自动帮你收窄错误类型,完全符合TS类型安全要求,代码修改如下:
首先导入所需类型:
import { AxiosError } from 'axios';
然后修改catch块逻辑:
catch (err) { // 先判断是不是Axios抛出的错误 if (axios.isAxiosError(err)) { // 此时err类型自动被收窄为AxiosError,可正常访问response属性 if (err.response?.status === 404) { window.alert('User not found'); } else if (err.response?.status === 401) { window.alert('Incorrect password'); } else { console.error(err); } } else { // 处理非Axios抛出的其他错误,比如本地代码运行报错 console.error('非请求错误:', err); } }
注:代码中加了可选链?.是为了兼容无响应返回的情况(比如网络超时、跨域拦截等,此时err.response会是undefined),避免运行时报错
方案2:类型断言(适合确定只会抛出Axios错误的场景)
如果你能确定该catch块捕获的错误100%是Axios请求错误,可以直接用类型断言指定类型,写法更简洁:
catch (err) { const axiosErr = err as AxiosError; if (axiosErr.response?.status === 404) { window.alert('User not found'); } else if (axiosErr.response?.status === 401) { window.alert('Incorrect password'); } else { console.error(err); } }
注意:该方案会跳过TS的类型校验,如果实际捕获了非Axios错误,运行时访问response属性会报错,生产环境不推荐使用
进阶用法:指定错误响应体类型
如果后端返回的错误响应有固定结构,你还可以给AxiosError加泛型,拿到类型提示:
// 假设后端错误响应体结构为 { code: number, msg: string } if (axios.isAxiosError<{ code: number, msg: string }>(err)) { console.log(err.response?.data.msg); // 可以拿到msg的类型提示 }
内容的提问来源于stack exchange,提问作者Daniel M
相关产品推荐
相关产品推荐

