Express Error Middleware

From Logic Wiki
Jump to: navigation, search


Register the error middleware after all the existing routes:

app.use(function(err, req, res, next) {
 // Log the exception and return a friendly error to the client.
 res.status(500).send(‘Something failed’);
});

But to make index.js cleaner move function to a middleware called middleware/error.js

module.exports = function(err, req, res, next) {
 // Log the exception and return a friendly error to the client.
 res.status(500).send(‘Something failed’);
}

and in index.js

const error = require('./middleware/error');
...
app.use(error);


To pass control to the error middleware, wrap your route handler code in a try/ catch block and call next()

try {
 const genres = await Genre.find();
 …
} 
catch(ex) {
 next(ex);
});

Adding a try/catch block to every route handler is repetitive and time consuming. Use express-async-errors module. This module will monkey-patch your route handlers at runtime. It’ll wrap your code within a try/catch block and pass unhandled errors to your error middleware.


To log errors use winston.