skip to Main Content

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


  1. 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);
      }
    };
    
    Login or Signup to reply.
  2. 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:

    try {
      await auth.signIn(data); // Use await here to catch any errors
    } catch (err) {
      console.log(err);
    }
    

    You may want to modify ur ‘signIn’ function instead to return the promise generated by ‘axios.post’.

    const signIn = (data: string) => {
      return axios.post(`url`, { data }).then((res) => {
        setUser(res.data);
      });
    };
    
    // Calling your code
    auth.signIn(data)
      .then(() => {
        // Success right here
      })
      .catch((err) => {
        console.log(err);
        // Handle the error here
      });
    

    Hope it helps bro 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search