I can’t catch an error in my React app.
I have a Context and in the Provider I have the following function
const signIn = async (data: string) => {
try {
const res = await axios.post(`url`, { data })
setUser(res.data)
}
catch (err: any) {
console.log(err)
throw new Error("something went wrong")
}
}
Then I’m calling the function.
try {
auth.signIn(data)
} catch (err: any) { // this catch doesn't work
console.log(err)
}
When I call it like that, the console log in the catch of signIn runs, throws the Error and the catch where I’m calling the function doesn’t catch and everything blows up. Like I don’t have a catch when I’m calling the function. (in the second example)
How can I fix this?
2
Answers
The issue you’re encountering is because
auth.signIn(data)
is an asynchronous function and you’re not waiting for it to complete before moving to the catch block in the second code snippet.To resolve this, you should use await when calling auth.signIn(data). This ensures that the Promise is either resolved or rejected before executing the catch block.
Note: You must ensure that the function where you are calling auth.signIn(data) is an async function, so that you can use the await keyword.
Here’s an example:
Looks like it may be a problem with the asynchronous behavior of ‘signIn’.
Try using ‘await’ in the ‘try – catch’ block. Something like this may work:
You may want to modify ur ‘signIn’ function instead to return the promise generated by ‘axios.post’.
Hope it helps bro 🙂