使用Express 4在Node.js中全局处理exception的最佳方法是什么?

AS我们在asp.net MVC中有Exceptionfilter,在express.js中我们有类似的function吗?

我试过以下文章,但没有find所需的解决scheme。

http://www.nodewiz.biz/nodejs-error-handling-pattern/

我也尝试了下面的app.js

process.on('uncaughtException', function (err) { console.log(err); }) 

参考文章: http : //shapeshed.com/uncaught-exceptions-in-node/

任何帮助将是可观的。

错误可能来自并捕获在不同的位置,因此build议在处理所有types错误的集中对象中处理错误。 例如,在以下地方可能会发生错误:

1.在Web请求中遇到SYNC错误的情况下,快速中间件

 app.use(function (err, req, res, next) { //call handler here }); 

2.CRON作业(计划任务)

你的初始化脚本

4.testing代码

5.某处发生错误

  process.on('uncaughtException', function(error) { errorManagement.handler.handleError(error); if(!errorManagement.handler.isTrustedError(error)) process.exit(1) }); 

未处理的承诺拒绝

  process.on('unhandledRejection', function(reason, p){ //call handler here }); 

那么当你发现错误时,把它们传递给一个集中的error handling程序:

  module.exports.handler = new errorHandler(); function errorHandler(){ this.handleError = function (error) { return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError); } 

欲了解更多信息,请阅读第4项“这里 (+其他最佳做法和超过35个引号和代码示例)

在expression中,标准的做法是将所有的error handling程序连接到一起。 准系统error handling程序看起来像

 // Handle errors app.use((err, req, res, next) => { if (! err) { return next(); } res.status(500); res.send('500: Internal server error'); }); 

与此同时,你将需要在发生的任何地方发现错误,并将它们作为next()的parameter passing。 这将确保捕获所有处理程序捕获错误。

在节点中添加全局exception处理程序是正在进行的事件。 使用process.on来捕捉它们。

 process.on('uncaughtException', (err) => { console.log('whoops! there was an error'); });