express handle errors code example

Example 1: express error handling

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

Example 2: express generator error handling

app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})

Example 3: err handling express

app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
      next(err) // Pass errors to Express.
    } else {
      res.send(data)
    }
  })
})