栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何将每个Express JS请求包装在域或trycatch中

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何将每个Express JS请求包装在域或trycatch中

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抛出异常的方式。这绝对是导致应用程序泄漏的原因,并使它更加不稳定。您可以使用此类错误处理来实现自定义的关机算法(例如,关闭已打开的连接)。有关正确使用域的更多信息,请参见文档。

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

更新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
内幕。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371349.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号