英文:
Catch block running before Try block in signup process
问题
I'm experiencing an issue where the catch block in my signup process is running before the try block. When I attempt to sign up, the catch block displays the error message before the success message is shown. This behavior is unexpected, as I would expect the try block to execute first.
Here is the relevant code snippet:
const onSignup = async (values: any) => {
try {
setLoading(true);
const response = await axios.post(`/api/users/signup`, values);
const responseData = response.data;
if (!responseData.error) {
toast.success("Signup success", successState);
router.push("/login");
} else {
if (responseData.error === "User already exists") {
toast.error("User already exists", errorState);
}
}
} catch (error: any) {
toast.error(
"An error occurred during sign in. Please try again later.",
errorState
);
} finally {
setLoading(false);
}
};
英文:
I'm experiencing an issue where the catch block in my signup process is running before the try block. When I attempt to sign up, the catch block displays the error message before the success message is shown. This behavior is unexpected, as I would expect the try block to execute first.
Here is the relevant code snippet:
const onSignup = async (values: any) => {
try {
setLoading(true);
const response = await axios.post(`/api/users/signup`, values);
const responseData = response.data;
if (!responseData.error) {
toast.success("Signup success", successState);
router.push("/login");
} else {
if (responseData.error === "User already exists") {
toast.error("User already exists", errorState);
}
}
} catch (error: any) {
toast.error(
"An error occurred during sign in. Please try again later.",
errorState
);
} finally {
setLoading(false);
}
};
答案1
得分: 1
在开发模式下,这可能是由于多次渲染而发生的 - 请查看此帖子 - https://stackoverflow.com/q/71847778/9640177
所以,实际上,您的捕获块不会被调用两次。您看到的错误来自前一个渲染。
英文:
In dev mode, this may be happening due to multiple renders - Check out this thread - https://stackoverflow.com/q/71847778/9640177
So, actually, your catch block is not called twice. The error you see is from the previous render.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论