[英]ExpressJS and Domain Error Handling in middleware
我期望綁定到域的中間件將由該域的錯誤處理程序處理。
在Express中,事實並非如此。
我創建了一個存儲庫來說明此問題
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注冊的域錯誤處理程序
而
var app = d.bind(function(req,res,next) {
throw new Error("error")
});
var server = http.createServer(app);
將錯誤正確地路由到域,而無需快遞。
對此有任何意見或想法嗎?
這只是一個不好的例子,因為express
將中間件包裝在try-catch中。 這有效:
app.get('/',d.bind(function(req,res,next) {
process.nextTick(function () {
throw new Error("error")
})
}));
通過節點js的文檔:
“此方法幾乎與domain.bind(callback)相同。但是,除了捕獲引發的錯誤之外,它還將攔截作為該函數的第一個參數發送的Error對象。”
我寫了一個演示代碼:
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可以解決所有錯誤同步和異步到域。 那就是定義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.