Processing error in asynchronous waterfall using expressjs

I do not understand why expressjs does not handle the error when it throws 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 prints a good error without crash serveur, but when I get / asyncerror this is a classic throw, print to stdout with a server crash.

Thanks for your help.

+4
source share
1 answer

This is because Express is never able to catch the exception that occurred in the /asyncerror example, because you are throwing it out of the async callback context, not the Express middleware context. In the general case, if you do not want the error condition in the asynchronous function to cause your node application to crash, report the error with a callback rather than sending it. In this case, you can call the next parameter, which receives your app.get , but you are not using it. Try 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')); }); }); 
+3
source

Source: https://habr.com/ru/post/1436330/


All Articles