【发布时间】:2021-12-10 12:59:56
【问题描述】:
我目前面临的问题是我不能使用从承诺拒绝返回的错误,因为它不能用 Typescript 输入。例如,当注册请求因用户名已被占用而失败时,我会返回 400 和 message username already taken。但我无法访问来自错误的消息,因为无法键入来自 try catch 的 error 对象。
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