I am trying to setup error handling for my express app and running into the following problem.
I defined an error middleware and add it as the last middleware:
I had this problem as well, but I couldn't figure out why it wasn't working even though I set my error handler after the app.user(app.router)
. As it turns out, I already had an error handler that I wasn't aware of.
Specifically, if you use the express cli to generate an app like I did, it will automatically add in this in:
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
Unfortunately for me, I added a bit more middleware to my app, which consequently obscured this statement and thus prevented my custom error handler from being called.
Simply remove that and then it should work properly.
On a side note, I should mention that the original solution still worked - even with the app.use(express.errorHandler())
.
app.all('*', function(err,req,res,next) {
console.log('This is a global error handler at route level....');
return next(err);
});