我不明白为什么expressjs在抛出async.waterfall时不会处理错误 var express = require('express'), app = express.createServer(), async = require('async');app.use(express.errorHandler({ dumpExceptions: true, showStack: true}));app
var express = require('express')
, app = express.createServer()
, async = require('async');
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
app.get('/error', function(req, res){
throw Error('Aie');
});
app.get('/asyncerror', function(req, res){
var that = this;
async.waterfall([
function(next){
console.log('1');
next("42", "2");
},
function(arg, next) {
console.log(arg);
res.json('ok');
}
], function(err){
console.log(this);
throw Error('Aie');
});
});
app.listen(8888, function(){
console.log('Listen on 0.0.0.0:8888');
});
当我GET /错误时,expressjs打印出一个漂亮的错误而没有崩溃服务但是当我获取/ asyncerror它是一个经典的抛出,在服务器崩溃的stdout上打印..
谢谢你的帮助.
这是因为Express永远不会有机会捕获/ asyncerror示例中抛出的异常,因为您从异步回调上下文而不是Express中间件上下文中抛出异常.通常,如果您不希望异步函数中的错误条件导致节点应用程序崩溃,请通过回调报告错误而不是抛出错误.在这种情况下,您可以调用app.get回调接收的下一个参数但您没有使用.试试这个:app.get('/asyncerror', function(req, res, next){
var that = this;
async.waterfall([
function(next){
console.log('1');
next("42", "2");
},
function(arg, next) {
console.log(arg);
res.json('ok');
next();
}
], function(err){
console.log(this);
next(Error('Aie'));
});
});
