使用Express 4在Node.js中处理全局异常的最佳方法?

Ash*_*mar 13 javascript asp.net-mvc jquery node.js express

AS我们在asp.net MVC中有异常过滤器,我们在node.js中还有类似的功能吗?

我试过以下文章,但没有找到理想的解决方案.

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

我也在app.js下面尝试过

process.on('uncaughtException', function (err) {
  console.log(err);
})
Run Code Online (Sandbox Code Playgroud)

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

任何帮助都会很明显.

Yon*_*tan 24

错误可能来自和捕获在各个位置,因此建议处理处理所有类型错误的集中对象中的错误.例如,以下位置可能会发生错误:

1.如果Web请求中出现SYNC错误,请执行中间件

app.use(function (err, req, res, next) {
//call handler here
});
Run Code Online (Sandbox Code Playgroud)

2.CRON工作(计划任务)

3.您的初始化脚本

4.测试代码

来自某个地方的未捕获错误

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

6.未处理的承诺拒绝

 process.on('unhandledRejection', function(reason, p){
   //call handler here
});
Run Code Online (Sandbox Code Playgroud)

然后,当您捕获错误时,将它们传递给集中的错误处理程序:

    module.exports.handler = new errorHandler();

function errorHandler(){
    this.handleError = function (error) {
        return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError);
    }
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请阅读bullet 4'(+其他最佳实践和超过35个引号和代码示例)


Swa*_*iri 5

明确地说,标准做法是附加一个catch all错误处理程序。准系统错误处理程序看起来像

// Handle errors
app.use((err, req, res, next) => {
    if (! err) {
        return next();
    }

    res.status(500);
    res.send('500: Internal server error');
});
Run Code Online (Sandbox Code Playgroud)

与此同时,您将需要捕获可能发生的任何错误,并将其作为参数传递给next()。这将确保catch all处理程序能够捕获错误。

  • 由于我已经在google上搜索并找到了直到现在的快速解决方案,但是我正在寻找类似asp.net mvc的异常过滤器 (2认同)

bol*_*lav 1

在节点中添加全局异常处理程序是process上的事件。用来process.on抓住他们。

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