简体   繁体   English

中间件中的ExpressJS和域错误处理

[英]ExpressJS and Domain Error Handling in middleware

I had an expectation that middleware that is bound to a Domain would be handled by the error handler for that domain. 我期望绑定到域的中间件将由该域的错误处理程序处理。

In Express this did not turn out to be true. 在Express中,事实并非如此。

I created a repository to illustrate this issue 我创建了一个存储库来说明此问题

https://github.com/rook2pawn/express-domains-issue https://github.com/rook2pawn/express-domains-issue

var app = express(); 
app.get('/',d.bind(function(req,res,next) {
    throw new Error("error")
}));
var server = http.createServer(app);

Will not route the error to the domain error handler registered at d 不会将错误路由到在d注册的域错误处理程序

whereas

var app = d.bind(function(req,res,next) {
    throw new Error("error")
});
var server = http.createServer(app);

Will properly route the error to the domain without express. 将错误正确地路由到域,而无需快递。

Requesting any comments or thoughts about this? 对此有任何意见或想法吗?

It's just a bad example, because express wraps middleware in try-catch. 这只是一个不好的例子,因为express将中间件包装在try-catch中。 This works: 这有效:

app.get('/',d.bind(function(req,res,next) {
    process.nextTick(function () {
      throw new Error("error")
    })
}));

By document of node js: 通过节点js的文档:

"This method is almost identical to domain.bind(callback). However, in addition to catching thrown errors, it will also intercept Error objects sent as the first argument to the function." “此方法几乎与domain.bind(callback)相同。但是,除了捕获引发的错误之外,它还将拦截作为该函数的第一个参数发送的Error对象。”

and I write a demo code: 我写了一个演示代码:

var domain = require('domain');
var fs = require('fs');

var d = domain.create();

require('http').createServer(function(req, res, next) {

d.on('error', function (err) {
    console.log(err);
    res.writeHead(500, "content-type: plain/text");
    res.end("Something missing!");
});


// This is for async
function readFile(filename, cb) {
    fs.readFile(filename, 'utf8', d.bind(function (er, data) {
        return cb(er, data ? JSON.parse(data) : null);
    }));
}
readFile("unknow file");


// This is for sync
(d.bind(function() {
    throw new Error();
}))();

}).listen(1337);

=> d.bind total can resolve all error sync and async to domain. => d.bind total可以解决所有错误同步和异步到域。 That is the definition 那就是定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM