发布于 2026-01-06 3 阅读
0

处理 TypeScript 中的 Axios 错误

处理 TypeScript 中的 Axios 错误

假设我们正在代码块axios中调用一个 APItry...catch来获取帖子列表。如果请求成功,我们将获得响应数据;否则,我们将收到代码catch块中的错误信息。

const fetchPosts = async () => {
  try {
    const response = await axios.get(
      "<https://jsonplaceholder.typicode.com/posts>"
    );
    // Do something with the response
  } catch (error) {
    // Need to handle this error
  }
};

Enter fullscreen mode Exit fullscreen mode

但问题在于 TypeScript 假定此error对象为 ` unknownObject` 类型。因此,TypeScript 不允许我们访问此error对象中的任何属性。
为了解决这个问题,我们可以error像这样断言对象类型。

import axios, {AxiosError} from "axios";

const fetchPosts = async () => {
  try {
    const response = await axios.get(
      "<https://jsonplaceholder.typicode.com/posts>"
    );
    // Do something with the response
  } catch (e) {
    const error = e as AxiosError;
    // Need to handle this error
  }
};
Enter fullscreen mode Exit fullscreen mode

但断言并非最佳实践,我们应该避免这样做。通过断言类型,你会强制 TypeScript 停止执行其工作。因此,这有时会造成问题。

一个好的解决方案

我们可以使用TypeGuard来处理这种情况,它axios也提供了typeguard错误处理机制。以下是它的示例:

const fetchPosts = async () => {
  try {
    const response = await axios.get(
      "<https://jsonplaceholder.typicode.com/posts>"
    );
    // Do something with the response
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.log(error.status)
      console.error(error.response);
      // Do something with this error...
    } else {
      console.error(error);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

我们还可以通过这种方式将通用类型传递给错误responserequest对象typeguard

interface ValidationError {
  message: string;
  errors: Record<string, string[]>
}

const fetchPosts = async () => {
  try {
    const response = await axios.get(
      "<https://jsonplaceholder.typicode.com/posts>"
    );
    // Do something with the response
  } catch (error) {
    if (axios.isAxiosError<ValidationError, Record<string, unknown>>(error)) {
      console.log(error.status)
      console.error(error.response);
      // Do something with this error...
    } else {
      console.error(error);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

注意:您也可以在.catch()方法中使用此方法。

想了解更多 TypeScript 的使用技巧,请在LinkedIn上关注我。

文章来源:https://dev.to/mdmostafizurrahaman/handle-axios-error-in-typescript-4mf9