如何将每个快速js请求包装在一个域或trycatch中

是否有可能将通过express.js进入domaintrycatch每一个请求包装看到trycatch信息 ?

我正在尝试创build一个“全部捕捉”(快速error handling程序中间件不捕获asynchronous调用),以确保我错过的任何错误都处理与发送给用户的500。

如果你有一个asynchronous的函数调用(例如process.nextTick()),那么它将超出expresserror handling程序的范围,从而完全终止进程。 因此,使用expressionerror handling程序将不会在所有情况下工作。

Express已经有error handling程序的实现。 它从连接inheritance。 要使用它,你需要添加它作为最后的中间件点(最后app.use(…)调用)。 例如:

 var express = require('express') , app = express(); app.use(app.router); app.use(express.errorHandler()); // app.get(...), app.post(...), app.listen(...), etc. 

如果你想用简单的500响应代码来处理所有的错误,你可以用你自己的函数replaceexpress.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. 

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

更新

当然你可以为每个请求使用域名。 您可以分别包装每个请求或使用包装来处理所有exception。 代码如下:

 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的原因是自然如何投掷工作。 这绝对是您的应用程序泄漏的原因,并使其更加不稳定。 您可以使用此类error handling来实现closures自定义algorithm(例如closures已打开的连接)。 有关正确使用域的更多信息可以在文档中find。

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

更新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的来源,没有任何魔法。 这仍然是泄漏的原因。 trycatch有引擎盖下的domain