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