繁体   English   中英

在 NodeJS 中处理错误的最佳方法

[英]Best way to handle errors in NodeJS

几周前我开始使用 NodeJS。 我想知道在 NodeJS 中处理错误的最佳方法是什么?

现在,我在我所有的控制器方法中都这样做。 例如:

exports.myMethod = async (req, res, next) => {
   try {
      // My method operations here
   } catch(err) {
      const email = new Email(); // This is a class that I create to notify me when an error happens. errorEmail(mailBody, mailSubject)
      await email.errorEmail(err, "Email Subject - Error");
   }
}

这是一个好方法吗? 我的意思是,是否有更好/更有效的方法来处理 NodeJS 中的错误?

谢谢

使用 Promises(或async / await )时的错误处理非常简单。 您不希望到处都有大量重复的错误处理代码和额外的 try/catch 块。

我发现最好的方法是将错误处理置于可能的最高级别(不在代码深处)。 如果抛出异常,或者 Promise 拒绝,则故障将渗透到您捕获并处理它的地步。 如果在适当的地方处理一次,则两者之间的所有内容都不必这样做。

所以你的代码可以像这样开始看起来更干净:

// module #1
exports.myMethod = async () => {
   // My method operations here
   return result;
}

// module #2
exports.anotherMethod = async () => {
  const result = await module1.myMethod();
  // do more stuff
  return anotherResult;
}

// module #3
exports.topMethod = () => {
  module2.anotherMethod()
    .then((res) => {
      console.log("all done", res);
    })
    .catch((err) => {
      const email = new Email(); // This is a class that I create to notify me when an error happens. errorEmail(mailBody, mailSubject)
      email.errorEmail(err, "Email Subject - Error")
        .then(() => console.log("done, but errors!", err);
    });
}

这里的好处是我唯一需要添加额外错误处理的地方就是顶部。 如果代码中的任何深处都失败了(并且它可以变得更深),那么它就会自然地返回到链上。

您可以自由地将.catch 语句放在两者之间的任何地方进行重试,或者如果您愿意,可以安静地处理预期的错误,但我发现使用.catch更干净,因为使用try/catch块包装代码部分。

暂无
暂无

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

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