繁体   English   中英

我如何处理在 javascript/nodejs 中的 catch 块中发生的错误

[英]How do I handle errors that occure in the catch block in javascript/nodejs

这是我的场景:

我正在创建一个用户 object 并将其保存到我的数据库中。 在此之后,我正在做其他可能导致错误的事情。 如果是这样,我需要“回滚”我对数据库所做的更改,这意味着我必须在 catch 块中再次从数据库中删除用户 object。 但是,此删除操作也可能会失败,这意味着我需要知道如何处理它?

当我说“处理”时,我的意思是我想将错误保存到我的数据库中。 所以我希望保存原始错误以及删除失败时的错误。 (我也知道将错误保存到数据库可能会失败,但如果确实如此,我无能为力,所以我只会让它发生)

那么我需要在 catch 块中使用嵌套的 try-catch 吗? 还是 catch 块会“捕获”它自己的错误?

// 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
}

此外,这只是我正在做的事情的一个简化示例,所以我不能不幸地向上移动 MoreCodeThatMightThrowAnError() 或使用数据库中的一些内置回滚功能。

你是对的,你需要使用另一个try-catch块。 尽管这看起来有点奇怪,但有时也是不可避免的。 有关更多信息,请参阅此问题

我建议像这样组织你的代码:

// 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);

所以基本上,您需要添加另一个try, catch块。 我相信您不必回滚您的更改,因为数据库是 ACID 兼容的,所以如果在操作过程中发生错误(即创建新用户),数据库将自动回滚整个操作。

catch块不会捕获其中发生的错误,因此您需要使用嵌套的 try...catch 语句。

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) {}
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM