express global error handler code example

Example 1: how to handle all error of all router in express

const handleErrorAsync = func => (req, res, next) => {
    func(req, res, next).catch((error) => next(error));
};

Example 2: express error handling

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Example 3: express error middleware

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