Error handling in Node.js + Express using promises

Using Node.js + Express (4) + Mongoose (using promises, not callbacks), I cannot figure out how to remove my error handling.

I have (fairly simplified):

app.get('/xxx/:id', function(request, response) {
    Xxx.findById(request.params.id).exec()
        .then(function(xxx) {
            if (xxx == null) throw Error('Xxx '+request.params.id+' not found');
            response.send('Found xxx '+request.params.id);
        })
        .then(null, function(error) { // promise rejected
            switch (error.name) {
                case 'Error':
                    response.status(404).send(error.message); // xxx not found
                    break;
                case 'CastError':
                    response.status(404).send('Invalid id '+request.params.id);
                    break;
                default:
                    response.status(500).send(error.message);
                    break;
            }
        });
});

Here, in the switch under the "Failed Failure" section, Erroris the error that I selected for a potentially valid identifier that was not found CastError- this is Cast to ObjectId, which Mongoose shot down for an invalid id, and a 500 error could be caused, for example, an error throw Error()like throw Err()(to raise ReferenceError: Err is not defined).

But, like this, each of my routes has this big big awkward switch for handling various errors.

? - ?

( , throw error; " ", ).

+4
1

. next() 404s. next(err) .

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

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

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');
  }
});

, json, :

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

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

All Articles