0

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

null200

例子:

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,
    })
  }
}
4

1 回答 1

1

Typescript 没有办法验证 axios 错误是您的代码可能引发的唯一可能错误,因此 typescript catch 块中的错误始终是unknownor any。您的编译器设置显然更喜欢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`
  }
}
于 2021-10-24T23:19:27.297 回答