Express 4 middleware error handler not being called Express 4 middleware error handler not being called express express

Express 4 middleware error handler not being called


The problem is, that your error handlers should always be at the end of your application stack. This means, that you can either move the error handler from your middleware to your app.js and use them after your requires (app.use()) or include your routes before your middleware.


Note: your error handler middleware MUST have 4 parameters: error, req, res, next. Otherwise your handler won't fire.


I had the same issue, spend the whole day on troubleshooting the issue. Finally, found a simple fix. This worked for me perfectly. You need to place the customer error handler right before the listener handler as below on the server instance file (App.js / server.js). Good luck :)

app.use((error, req, res, next) => {    if (res.headersSent) {        return next(err)    }    res.status(500).send('INTERNAL SERVER ERROR !')  });app.listen(3000, function() {    console.log('Node app is running on port 3000');});module.exports = app;