【问题标题】:Axios & Typescript give error from promise rejection a typeAxios 和 Typescript 给出一个类型的 promise 拒绝错误
【发布时间】:2021-12-10 12:59:56
【问题描述】:

我目前面临的问题是我不能使用从承诺拒绝返回的错误,因为它不能用 Typescript 输入。例如,当注册请求因用户名已被占用而失败时,我会返回 400message username already taken。但我无法访问来自错误的消息,因为无法键入来自 try catcherror 对象。
axios 有什么方法可以处理这种情况,并且可以让我使用自定义类型访问错误对象吗?
或者我应该在数据下创建一个错误对象,然后在服务器有200 时将其返回为null,或者返回一个错误对象?

例子:

export interface ErrorRes {
  statusCode: number;
  error: string;
  message: string;
}

export interface ISignupRes {
  token: string;
  user: IUser;
  message: string;
}
const handleSignUp = async () => {
  setLoading(true)
  try {
    const { data, status }: { data: ISignupRes; status: number } =
      await coreApi.post('/auth/signup', {
        email,
        username,
        firstname,
        lastname,
        password,
      })
    if (status === 200) {
      Storage.save(true, 'token', data.token)
      addNotification({
        type: 'success',
        message: data.message,
      })
    } else {
      // this never get's called because if the response returns an error it get's catched
      addNotification({
        type: 'error',
        message: data.message,
      })
    }
    setLoading(false)
  } catch (error) {
    // the error is of type `unkown` to I can't access `error.message`
    setLoading(false)
    addNotification({
      type: 'error',
      message: error.message,
    })
  }
}

【问题讨论】:

    标签: reactjs typescript axios try-catch unhandled-promise-rejection


    【解决方案1】:

    Typescript 没有办法验证 axios 错误是您的代码可能引发的唯一可能错误,因此 typescript catch 块中的错误始终是 unknownany。您的编译器设置显然更喜欢unknown

    要将错误视为其他错误,您需要输入一些代码来检查抛出了什么类型的东西,或者您需要使用类型断言来坚持打字稿您知道类型是什么。幸运的是,axios 库包含一个可以为您进行检查的辅助函数,并且它具有适当的类型来缩小错误对象的范围:

    } catch (error) {
      if (axios.isAxiosError(error) {
        // inside this block, typescript knows that error's type is AxiosError<any>
        setLoading(false)
        addNotification({
          type: 'error',
          message: error.message,
        })
      } else {
        // In this block, error is still of type `unknown`
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-10-08
      • 2017-05-27
      • 2018-02-25
      • 2016-09-18
      • 2018-01-21
      • 1970-01-01
      • 2016-05-18
      相关资源
      最近更新 更多