它会转到突变中的 onError,但是在 try catch 中,下一个响应的状态为 200,因此它不会执行 catch 方法。我应该怎么做,这样如果它转到 onError,它就会捕获。 我也愿意接受任何可以正确返回/结束函数的解决方案
const useValidatePassword = () =>{
return useMutation({
mutationFn: async (data: any) => {
const body: validatePasswordPayload =
{
UserName: data.username,
Password: data.currentPassword,
};
await apiAccountSettings.validatePassword(tenantName, body);
}
,
onSuccess: () => {
return true
},
onError: (data) => {
toast.error(t('Current password is incorrect'));
},
mutationKey: ['ValidatePassword', { tenant: tenantName }],
});
}
const {mutate: validatePassword, error} = useValidatePassword();
Somefn()=>{
try {
await validatePassword(validatePayload);
} catch (error) {
toast.error(t("Something went wrong"));
return
}
}
通过在
onError
回调中抛出错误,可以确保错误传播到 try-catch
块。
new Promise
validatePassword
调用的包装器确保 try-catch
块可以等待突变结果并捕获引发的任何错误。
const useValidatePassword = () => {
return useMutation({
mutationFn: async (data: any) => {
const body: validatePasswordPayload = {
UserName: data.username,
Password: data.currentPassword,
};
await apiAccountSettings.validatePassword(tenantName, body);
},
onSuccess: () => {
return true;
},
onError: (error) => {
toast.error(t('Current password is incorrect'));
throw error; // Throw the error to propagate it
},
mutationKey: ['ValidatePassword', { tenant: tenantName }],
});
};
const { mutate: validatePassword } = useValidatePassword();
const Somefn = async () => {
try {
await new Promise((resolve, reject) => {
validatePassword(validatePayload, {
onSuccess: resolve,
onError: reject,
});
});
} catch (error) {
toast.error(t("Something went wrong"));
return;
}
};