4

我不明白为什么 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 这是一个经典的抛出,打印在 stdout 上并出现服务器崩溃..

谢谢你的帮助。

4

1 回答 1

3

It's because Express never has the opportunity to catch the exception that's thrown in the /asyncerror example as you're throwing it from within an async callback context and not an Express middleware context. In general, if you don't want an error condition in an async function to crash your node app, report the error via the callback instead of throwing it. In this case you can call the next parameter that your app.get callback is receiving but you're not using. Try this instead:

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'));
        });
});
于 2012-09-26T12:19:05.463 回答