【问题标题】:Axios with TypeScript: How to tell Axios the error response shapeAxios 与 TypeScript:如何告诉 Axios 错误响应形状
【发布时间】:2021-06-30 12:48:21
【问题描述】:

我有一个 API 路由(使用 Next.js API routes),成功时具有特定响应形状,发生错误时具有特定响应形状。

export type ApiErrorResponse = { message: string };

export type SuccessResponse = {
  user: UserSession | null;
};

export type GetCurrentUserHandlerResponse = ApiErrorResponse | SuccessResponse;

const getCurrentUserHandler: NextApiHandler<GetCurrentUserHandlerResponse> = () => { /* ... */ };

如何根据错误告诉 Axios 响应的形状?

当我像这样抽象出请求时:

const getCurrentUserRoute = '/api/user';

const getCurrentUserRequest = () =>
  axios.get<GetCurrentUserHandlerResponse>(getCurrentUserRoute);

并使用getCurrentUserRequest 我总是必须区分.then.catch 的响应是成功形式还是错误形式。

理想情况下,我正在寻找这样的东西:

const getCurrentUserRequest = () =>
  axios.get<SuccessResponse, ApiErrorResponse>(getCurrentUserRoute);

最终我希望 TypeScript 能够做到这一点:

getCurrentUserRequest()
  .then((response) => {
    // now TS knows response.data is of the shape { user: UserSession | null; }
  })
  .catch((error) => {
    // now TS knows error.response.data is { message: string; }
  });

有没有办法用 TypeScript 做到这一点?

【问题讨论】:

    标签: typescript axios


    【解决方案1】:

    我认为您可能假设错误的代码路径与使用 axios 获得的代码路径不同。更常规的做法是,您会以异步/等待方式实现这一点,并且在“快乐路径”中,您总是假设数据的形状正确。

      try {
        const response = await apiClient.get<MyObj>('/endpoint');
        const myObj: MyObj = response.data;
        return myObj;
      } catch (err) {
        // use explicit separation of error cases here
      }
    

    只有在 catch 子句中你必须处理错误,在这种情况下,你总是必须引入某种typeguard 来断言请求正文的经过验证的类型,因为有多个错误可能发出网络请求时出现。

    ...或者您的情况是不是在 HTTP 层作为错误出现的错误?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-21
      • 2019-12-09
      • 2022-01-18
      • 2020-10-22
      • 2020-04-12
      • 2020-11-05
      • 2020-07-26
      • 2017-11-07
      相关资源
      最近更新 更多