Question

I don't see why expressjs don't handle error when it's throw in 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');
});

When i GET /error , expressjs print a nice error without crash serveur but when i GET /asyncerror it's a classic throw, print on stdout with server crash ..

Thx for your help.

Was it helpful?

Solution

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'));
        });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top