Typescript 和 AxiosError:当出现 AxiosError 时,Axios 有两个嵌套响应,而不是一个嵌套响应

问题描述 投票:0回答:1

我的 api 在任何地方都工作得绝对正常,除非我尝试对潜在的 Axios 错误执行 if 块。这是因为

status
位于
response.response.status
而不是
response.status
,所以 Typescript 会抛出错误
Property 'response' does not exist on type 'AxiosResponse<any, any>'.

有人可以帮我吗?

在不存在 AxiosError 的情况下工作:

postBoundary: async (boundary: CreateBoundary) => {
    const response = await axios.post(
      `${config.baseApiPath}boundary`,
      boundary
    );
    return response.data; //returns correctly
  }

无法使用 Axios 出现错误:

postBoundary: async (boundary: CreateBoundary) => {
        const response = await axios.post(
          `${config.baseApiPath}boundary`,
          boundary
        );
        // when response has an Axios error response.status 
        // doesn't exist because there are two nested responses
        if (response.response.status === 
            HttpStatusCode.PayloadTooLarge) {
             throw new Error("Error");
         }
        return response.data;
        }
reactjs typescript axios typescript-typings httpresponse
1个回答
0
投票

这是因为当 Axios 请求失败时,错误对象的结构与成功响应的结构不同。

import { AxiosError, HttpStatusCode } from 'axios';

postBoundary: async (boundary: CreateBoundary) => {
  try {
    const response = await axios.post(
      `${config.baseApiPath}boundary`,
      boundary
    );
    return response.data;
  } catch (error) {
    // First check if it's an AxiosError
    if (error instanceof AxiosError) {
      // Now we can safely access error.response
      if (error.response?.status === HttpStatusCode.PayloadTooLarge) {
        throw new Error("Payload too large");
      }
    }
    // Re-throw any other errors
    throw error;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.