If some underlying component throws an error, how do I get to inform the express.js stack about it? I am using an underlying data access framework which occasionally throws specific errors (for instance, when a record is not found in the DB).
Does express.js offer a way to jump straight to a 500 error handler, and redirect the response to a corresponding page? Unfortunately, I do not see a direct way to use the standard express.js way (using a next middleware handler) unless maybe if I use try...catch everywhere, which is also a bit of overhead
Usually you don't redirect to a 500 page. What you do is let the exception propagate and node.js will do a 500 for you if an exception was thrown.
I have some related rules I follow. Maybe you'll find them useful:
res.send('Error', 500);Something for those who are still looking for an answer like me:
1- Use express default errorHandler middleware
app.use(express.errorHandler());
Or
2- Supply your own error handling middleware:
app.use(function (error, req, res, next) {
res.status(500);
res.render("500.jade", {});
});
Ideally you would want to use the first option on DEV and the second one on PROD
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use((function (error, req, res, next) {
res.status(500);
res.render("500.jade", {});
});
Note: the error handler should be strategically placed below the app.router