Error handling in Node.js + Express using promises Error handling in Node.js + Express using promises mongoose mongoose

Error handling in Node.js + Express using promises


I would create middleware to handle errors. Using next() for 404s. and next(err) for other errors.

app.get('/xxx/:id', function(req, res, next) {  Xxx.findById(req.params.id).exec()    .then(function(xxx) {      if (xxx == null) return next(); // Not found      return res.send('Found xxx '+request.params.id);    })    .then(null, function(err) {      return next(err);    });});

404 handler

app.use(function(req, res) {  return res.send('404');});

Error handler

app.use(function(err, req, res) {  switch (err.name) {    case 'CastError':      res.status(400); // Bad Request      return res.send('400');    default:      res.status(500); // Internal server error      return res.send('500');  }});

You can improve upon this more by sending a json response like:

return res.json({  status: 'OK',  result: someResult});

or

return res.json({  status: 'error',  message: err});