Error handling in ExpressJS


Define errorhandling middleware like other middleware, except with four arguments instead of three, specifically with the signature (err, req, res, next). For example:

app.use(function(err, req, res, next) {
	console.error(err.stack);
	res.status(500).send('Error while trying to Access');
});

The Default Error Handler

Express comes with an in built error handler, which takes care of any errors that might be encountered in the app. This default errorhandling middleware is added at the end of the middleware stack.

If you pass an error to next() and you do not handle it in an error handler, it will be handled by the builtin error handler the error will be written to the client with the stack trace. The stack trace is not included in the production environment.

So when you add a custom error handler you will want to delegate to the default error handling mechanisms in express, when the headers have already been sent to the client.

function errorHandler(err, req, res, next) {
	if (res.headersSent) {
		return next(err);
	}
	res.status(500);
	res.render('error', { error: err });
}