I am building an app in nodejs and express. Can anybody help me to understand the difference between the following pieces of code:
var app = express();
app.use(function(err, req, res, next){
console.error(err);
res.render('home.ejs', {message:'Something broke!'});
});
and
var domain = require('domain');
var d = domain.create();
d.on('error', function(err) {
console.error(err);
res.render('home.ejs', {message:'Something broke!'});
});
Are the two pieces of code alternative? If yes, which one is more reliable in order to avoid the app crashing on production?
Express wraps each
function (req, res, next) {}
in a try/catch. Which catches many errors, but not async errors. Domains catch async errors. However catching the error and handling it are two different things.If you next the error (aka
d.on('error', next);
) it will end up in going to express error middleware, just like in your first example.So instead of thinking about express vs domains, think try/catch vs domains. Express should be used to handle the error in either case.
I've managed to get async error handling working with domains with this middleware:
I'm currently testing it in on my servers, but looks good for me:). I also created npm module. You can take a look at it:
npmjs.org - express-async-error
Hope this helps. :)