Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

handling error in async waterfall with expressjs

handling error in async waterfall with expressjs

Problem

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.

Problem courtesy of: lemulot

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'));
        });
});
Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

handling error in async waterfall with expressjs

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×