中间件中的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.
在Express中,事实并非如此.
In Express this did not turn out to be true.
我创建了一个存储库来说明此问题
I created a repository to illustrate this 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);
不会将错误路由到在d注册的域错误处理程序
Will not route the error to the domain error handler registered at d
而
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?
推荐答案
通过节点js的文档:
此方法几乎与domain.bind(callback)相同.但是,除了捕获引发的错误之外,它还将拦截作为该函数的第一个参数发送的Error对象."
"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."
然后我编写了一个演示代码:
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可以解决所有错误同步和异步到域的问题.那就是定义
=> d.bind total can resolve all error sync and async to domain. That is the definition
这篇关于中间件中的ExpressJS和域错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!