Home > Back-end >  How do I handle errors that occure in the catch block in javascript/nodejs
How do I handle errors that occure in the catch block in javascript/nodejs

Time:12-27

Here is my scenario:

I am creating a user object which I am saving to my database. After this I am doing something else which may result in an error. If so, I need to "rollback" the changes I made to the database, meaning I have to delete the user object from the database again in the catch block. However, this delete action may also fail meaning I need to know how I handle this?

When I say "handle" what I mean is I would like to save the error to my database. So I want the original error to be saved and also the error in the case the deleting fails. (I also know saving the error to the database might fail, but if it does there isnt much I can do so I'll just let it happen)

So do I need to use a nested try-catch inside the catch block? or will the catch block "catch" its own errors?

// psuedocode-ish illustation of what I'm working with
try {
  const new_user = Database.save(user);
  MoreCodeThatMightThrowAnError(); // imagine this throws an error
}
catch (error) {
  if (new_user) Database.delete(user); // Do I need this inside a nested try-catch?
  console.log(error);
  Database.save(error); // dont care if this fails
}

Also, this is just a simplified example of what I am doing so I cannot just move the MoreCodeThatMightThrowAnError() up or use some build in rollback functionality from my database unfortunantly.

CodePudding user response:

You are correct, you need to use another try-catch block. Even though it' seems a bit strange, it's sometimes unavoidable. See this question for more.

CodePudding user response:

I would suggest organizing your code like this:

// psuedocode representation
try {
  const new_user = Database.save(user);
  try {
    const otherCode = Database.otherThingThatCauseError();
  } catch(err) {
    console.log(err)
  }
  // ... and so on
} catch(err) {
  // no need to rollback, most databases are ACID-compliant
  console.log(err);

So basically, you would want to add another try, catch block. I believe that you won't have to rollback your changes since databases are ACID compliant, so if something wrong happens in the middle of an operation (i.e. creating a new user), the database will automatically roll back the whole operation.

CodePudding user response:

A catch block does not catch errors that occur inside of it, so you would need to use a nested try...catch statement.

try {
  const new_user = Database.save(user);
  MoreCodeThatMightThrowAnError(); // imagine this throws an error
}
catch (error) {
  console.log(error);

  try {
    if (new_user) Database.delete(user);
  } catch (error2) {
    console.log(error2);

    try {
      Database.save(error2);
    } catch (error3) {}
  }
}
  • Related