Himmators Himmators - 5 months ago 31
Node.js Question

A generic catch-version for exeptions?

I have a sequelize database that validates data and throws errors.

I know I can do something like this to catch and output my errors:

User.build()
.catch(Sequelize.ValidationError, function (err) {
// respond with validation errors
return res.status(422).send(err.errors);
})
.catch(function (err) {
// every other error
return res.status(400).send({
message: err.message
});


But I don't want to add it to every single request, is there some generic way to catch theese errors?

Answer

You can add a custom method to req (or res) that will resolve the promise and handle any errors:

app.use((req, res, next) => {
  req.resolve = (promise) => {
    return promise.catch(Sequelize.ValidationError, err => {
      // respond with validation errors
      return res.status(422).send(err.errors);
    }).catch(err => {
      // every other error
      return res.status(400).send({ message: err.message });
    });
  });
  next();
});

Usage (provided that the middleware above is added before your routes):

router.post('/user', (req, res) => {
  req.resolve(User.build()).then(user => res.json(user));
});