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

TypeScript与AxiosError问题:错误响应嵌套两层引发类型报错

解决Axios错误处理中的TypeScript类型问题

你的问题核心是搞混了Axios成功响应和错误对象的结构:

  • 请求成功时,await axios.post()返回的是AxiosResponse类型,直接通过response.status、response.data就能访问状态码和响应体。
  • 请求失败(比如返回413 Payload Too Large)时,Axios会抛出AxiosError对象,服务器返回的错误响应数据存放在error.response里,这时候才能通过error.response.status获取状态码。

之前的代码错误地在成功响应里访问response.response,这不符合类型定义,所以TypeScript会报错。

正确的处理方式

用try/catch捕获Axios抛出的错误,在catch块里专门处理AxiosError:

import { AxiosError } from 'axios';

postBoundary: async (boundary: CreateBoundary) => {
  try {
    const response = await axios.post(
      `${config.baseApiPath}boundary`,
      boundary
    );
    // 请求成功直接返回数据
    return response.data;
  } catch (error) {
    // 先判断是否为AxiosError类型
    if (error instanceof AxiosError) {
      // 检查服务器返回的错误状态码
      if (error.response?.status === HttpStatusCode.PayloadTooLarge) {
        throw new Error("请求体过大,请压缩后重试");
      }
      // 可扩展处理其他错误状态码
      throw new Error(`请求失败: ${error.message}`);
    }
    // 处理非Axios类型的未知错误
    throw new Error("未知错误");
  }
}

关键说明

  • 必须用try/catch包裹Axios请求,因为请求失败时Axios是抛出错误,而非返回带错误的响应。
  • 使用error instanceof AxiosError做类型守卫,让TypeScript识别错误类型,才能安全访问error.response。
  • 用可选链?.处理error.response可能为undefined的情况(比如网络错误、请求未到达服务器时,就不会有服务器返回的响应)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 10:22:37