Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I'm not able to catch this error in React

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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:

const someAsyncFunction = async () => {
  try {
    await auth.signIn(data);
  } catch (err: any) {
    console.log(err);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading