11

是否可以将来自 express.js 的每个请求包装在 a 中domaintrycatch 在此处查看 trycatch 信息

我正在尝试创建一个“全部捕获”(快速错误处理程序中间件不捕获异步调用),以确保我错过的任何错误都通过发送给用户的 500 得到处理。

如果您有一个异步函数调用(例如 process.nextTick()),那么它将超出 express 错误处理程序的范围,从而完全终止该进程。因此,使用 express 错误处理程序并非在所有情况下都有效。

4

1 回答 1

10

Express 已经有错误处理程序实现。它从connect继承。要使用它,您需要将其添加为最后一个中间件点(最后一个 app.use(...) 调用)。例如:

var express = require('express')
  , app = express();

app.use(app.router);
app.use(express.errorHandler());

// app.get(...), app.post(...), app.listen(...), etc.

如果你想用简单的 500 响应代码处理所有错误,你可以express.errorHandler()用你自己的函数替换。在这种情况下,您的代码将如下所示:

var express = require('express')
  , app = express();

app.use(app.router);
app.use(function(err, req, res, next){
  if (!err) return next();
  res.send(500);
});

// app.get(...), app.post(...), app.listen(...), etc.

有关这种方式的更多信息可以在代码中的快速错误示例注释中找到

更新

当然,您可以为每个请求使用域。您可以单独包装每个请求或使用包装路由器来处理所有异常。代码如下:

var express = require('express')
    , http = require('http')
    , app = express()
    , domain = require('domain');

//app.use(app.router);
app.use(function(req, res, next){
    var d = domain.create();
    d.on('error', function(er) {
        console.log('error, but oh well', er.message);
        res.send(500);
    });

    // explicitly add req and res
    d.add(req);
    d.add(res);

    d.run(function() {
        app.router(req, res, next);
    });
});

app.get('/', function(req,res){
    process.nextTick(function(){
        throw new Error('Check Error');
    });
});

http.createServer(app).listen(3000, function(){
    console.log('Express server listening on port 3000');
});

!!但!!永远不要在生产中使用它。其原因本质上是 JS throw 的工作方式。这肯定会导致您的应用程序泄漏并使其更加不稳定。您可以使用此类错误处理来实现自定义关闭算法(例如关闭已打开的连接)。有关正确使用域的更多信息,请参阅文档

要监控泄漏,您可以使用以下技术本文中的技术。

更新 2

我只是不能让这个没有完成。trycatch代码:

var express = require('express')
    , http = require('http')
    , app = express()
    , domain = require('domain')
    , trycatch = require('trycatch');

//app.use(app.router);
app.use(function(req, res, next){
   trycatch(function(){
           app.router(req, res, next);
       }, function(er){
           console.log(er.message);
           res.send(500);
       });
});

app.get('/', function(req,res){
    process.nextTick(function(){
        throw new Error('Check Error');
    });
});

http.createServer(app).listen(3000, function(){
    console.log('Express server listening on port 3000');
});

我审查了来源,trycatch没有任何魔法。它仍然是泄漏的原因。trycatchdomain引擎盖下。

于 2013-10-30T20:45:55.913 回答