在expressjsasynchronous瀑布处理错误

我不明白为什么expressjs在抛出async.waterfall时不处理错误

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打印一个很好的错误没有崩溃serveur,但是当我得到/ asyncerror这是一个经典的扔,在服务器崩溃的标准输出打印..

Thx为您提供帮助。

这是因为Express从来没有机会捕获/asyncerror示例中抛出的exception,因为您从asynccallback上下文中而不是Express中间件上下文中抛出该exception。 一般来说,如果你不希望asynchronous函数中的错误条件导致节点应用程序崩溃,请通过callback报告错误而不是抛出错误。 在这种情况下,你可以调用next参数,你的app.getcallback正在接收,但你没有使用。 试试这个:

 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')); }); });