【问题标题】:Catching errors in Node.js在 Node.js 中捕获错误
【发布时间】:2016-11-06 13:29:31
【问题描述】:

在我的 Node.js 应用程序中,我想捕获所有未处理的错误并将它们写入日志。

目前我用 try/catch 块包装每个边缘点代码,但工作量很大。我需要一种在一个地方捕获所有错误的方法,例如 ASP.Net 中的 Global.asax application_error,所以不要这样:

function a(){
 try{
 var wrong = 3 / 0;
 } catch(err){
   console.log(err);
 }
}

function b(){
 try{
 var wrong = 3 / 0;
 } catch(err){
   console.log(err);
 }
}

function c(){
 try{
 var wrong = 3 / 0;
 } catch(err){
   console.log(err);
 }
}

我只会有这样的东西:

function a() {
 var wrong = 3 / 0;
}

function b() {
 var wrong = 3 / 0;
}

function c() {
 var wrong = 3 / 0;
}

function errorHandler(err) {
 console.log(err);
}

任何帮助将不胜感激!

【问题讨论】:

标签: javascript node.js error-handling


【解决方案1】:

您可以使用未捕获的异常从一处捕获所有错误。

process.on('uncaughtException', function (err) {
  console.error((new Date).toUTCString() + ' uncaughtException:', err.message)
  console.error(err.stack)
  process.exit(1)
})

https://shapeshed.com/uncaught-exceptions-in-node/

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-05-28
  • 2011-02-23
  • 2013-07-07
  • 2012-12-12
  • 2016-02-27
  • 2016-10-05
  • 2019-03-02
  • 1970-01-01
相关资源
最近更新 更多