arb / celebrate

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

added status code override #211

Closed adarah closed 3 years ago

adarah commented 3 years ago

The current behaviour is to always return the same HTTP status code. This commit allows users to override the returned status code from individual CelebrateErrors.

arb commented 3 years ago

Have you checked out the arguments to errors()? Does that solve the use case? I'd like to not add status code here because that is an HTTP layer concern and the original intent of CelebrateError was to act as a bucket of errors.

Also, have you looked into writing your own error handler?

adarah commented 3 years ago

Hi, first of all thanks for the great library! For some context, here's what I'm trying to do: I wrote a custom Joi validator using any.external(), and it makes some checks in the database to see if the resource exists. If it doesn't, then I would like to return a 404 error instead of 400.

With that said, I did check the errors() function, and I could be mistaken, but I think it doesn't quite solve my use-case since it only lets me globally set the same HTTP status code to all errors generated by Joi, and what I would like to do is to only override the status code of errors generated by this specific validator. And about writing my own CelebrateError handler, I'm not sure how I would get status code information without inserting some kind of option in the CelebrateError object itself, so this is why I wanted this override option in the error object itself. If you have some suggestion on how to properly handle this, that would be great!

arb commented 3 years ago

Just spitballing ideas here... what if you used the .meta API for your external call and put something you can key off of in there? Then we could update celebrate so that in addition to including the Joi error in details, include the schema it was validated against so you could pull that out in a custom error handler and then conditionally send a different status code.

How does that idea strike you?

adarah commented 3 years ago

Sounds good, I will try to implement these changes in the upcoming days and see how it goes.

arb commented 3 years ago

Closing due to inactivity