arb / celebrate

A joi validation middleware for Express.
MIT License
1.33k stars 66 forks source link

how to override the default error code of 400 to a more specific 422? #113

Closed j-d-carmichael closed 5 years ago

j-d-carmichael commented 5 years ago

I am writing a collection of micro services that will work in combination with a few others, not all written in node. I need to align the error status code with the rest of the services, to http status code 422. This package is nice and simple but how can i acheive this, cannot see anything in the readme on changing it from 400.

j-d-carmichael commented 5 years ago

As some what of a dirty hack, but dictating the status code feels like it should be done in the "errors" middleware:

export default () => {
  return (err, req, res, next) => {
    if (err.joi) {
      res.status(422).json(err)
    } else {
      next(err)
    }
  }
}
arb commented 5 years ago

@johndcarmichael please check https://github.com/arb/celebrate#errors and https://github.com/arb/celebrate#iscelebrateerr about celebrate errors and the common use for isCelebrate.

Basically, write your own celebrate error handler and check isCelebrate(err) to determine if the error came from a celebrate validation failure.