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

TypeScript中捕获Axios自定义服务器错误的类型问题求解

解决TypeScript中Axios错误无法访问response属性的问题

你遇到的问题根源是:Axios抛出的错误并非原生Error类型,而是它自定义的AxiosError类型——只有这个类型包含response等专属属性,直接断言成Error自然会触发类型报错。下面是几种可行的解决方法:

方法1:直接断言为AxiosError类型

导入Axios提供的AxiosError类型,在catch块中将错误断言为该类型,同时注意处理response可能为undefined的情况(比如网络错误时不会返回response):

import axios, { AxiosError } from 'axios';

const handleLogin = async (formData: FormData) => {
  const email = formData.get("email");
  const password = formData.get("password");

  axios
    .get("http://localhost:8000/sanctum/csrf-cookie")
    .then(async () => {
      try {
        const response = await axios.post(
          "http://localhost:8000/api/login",
          {
            email,
            password,
          },
          {
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }
        );

        console.log(response.data);
      } catch (error: unknown) {
        const axiosError = error as AxiosError;
        // 使用可选链避免response为undefined时的运行时错误
        console.log(axiosError.response?.data);
      }
    })
    .catch((error: unknown) => {
      const axiosError = error as AxiosError;
      console.log(`Error: ${axiosError.message}`);
    });
};

方法2:用类型守卫实现严谨的类型推断

如果想让类型检查更安全,可编写一个类型守卫函数,明确判断错误是否为AxiosError:

import axios, { AxiosError } from 'axios';

// 自定义类型守卫函数
function isAxiosError(error: unknown): error is AxiosError {
  return typeof error === 'object' && error !== null && 'response' in error;
}

const handleLogin = async (formData: FormData) => {
  const email = formData.get("email");
  const password = formData.get("password");

  axios
    .get("http://localhost:8000/sanctum/csrf-cookie")
    .then(async () => {
      try {
        const response = await axios.post(
          "http://localhost:8000/api/login",
          {
            email,
            password,
          },
          {
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }
        );

        console.log(response.data);
      } catch (error: unknown) {
        if (isAxiosError(error)) {
          // 这里TypeScript会自动推断error为AxiosError类型
          console.log(error.response?.data);
        } else {
          // 处理非Axios抛出的错误
          console.log('Unknown error:', error);
        }
      }
    })
    .catch((error: unknown) => {
      if (isAxiosError(error)) {
        console.log(`Error: ${error.message}`);
      } else {
        console.log('Unknown error:', error);
      }
    });
};

方法3:用async/await优化代码结构

把嵌套的.then改成async/await,让代码逻辑更清晰,同时统一错误处理:

import axios, { AxiosError } from 'axios';

const handleLogin = async (formData: FormData) => {
  const email = formData.get("email");
  const password = formData.get("password");

  try {
    await axios.get("http://localhost:8000/sanctum/csrf-cookie");
    
    const response = await axios.post(
      "http://localhost:8000/api/login",
      { email, password },
      {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      }
    );

    console.log(response.data);
  } catch (error: unknown) {
    const axiosError = error as AxiosError;
    if (axiosError.response) {
      // 处理服务器返回的错误响应
      console.log(axiosError.response.data);
    } else {
      // 处理网络错误或其他无响应的错误
      console.log(`Error: ${axiosError.message}`);
    }
  }
};

关键注意点

  • Axios错误分两种场景:有响应的错误(如4xx/5xx状态码)和无响应的错误(如网络中断),必须处理response为undefined的情况,避免运行时报错。
  • 确保已安装axios(自带类型定义,无需额外安装@types/axios)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:13:27