我不明白为什么 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/error 时,expressjs 会打印一个很好的错误,而不会导致服务器崩溃,但是当我 GET/asyncerror 时,这是一个经典的错误,在标准输出上打印服务器崩溃..
感谢您的帮助。
最佳答案
这是因为 Express 从来没有机会捕获 /asyncerror
示例中抛出的异常,因为您是从 async
回调上下文中抛出它,而不是表达中间件上下文。通常,如果您不希望异步函数中的错误条件使您的 Node 应用程序崩溃,请通过回调报告错误而不是抛出错误。在这种情况下,您可以调用 app.get
回调正在接收但您未使用的 next
参数。试试这个:
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'));
});
});
关于node.js - 使用 expressjs 处理异步 waterfall 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598559/