express-openapi-validator
express-openapi-validator copied to clipboard
Custom error handler for request validation
Hello. For our APIs we have error messages with certain structure. Therefore it would be nice to be able to define own error handler for request validation, similar to the onError prop for validateResponses you already have.
Proposed solution
We should have the possibility to define the handler as a property for the validateRequests. For example:
validateRequests: {
onError: (error) => throw customError(error)
}
My current ugly workaround
Currently a catch the validation error in the error handling middleware, try to find out that this is really the validation error, format it and send to the client:
const errorHandler = (err, req, res, next) => {
// do not want this checks
if (err.errors && err.status) {
return res.status(err.status).send({
...createError({
type: err.name,
message: "Request violates API Specification",
code: err.status,
}),
errors: err.errors,
});
};
Let me know what you think about it and if there are any better alternatives for my workaround!
Your might check if the error is of type HttpError
@cdimascio Yes, but ideally I would avoid all checks here to keep the code base consistent, clean and explicit. Otherwise it looks like dirty hack, in my opinion. I'm tired to explain to my colleagues why I'm doing this.
So, if you think this is a luxury problem that only I have and it's not worth spending time on, close the issue. Then I have to live with it. Otherwise, I would try to find a simple solution for it and create a PR.
Just raising hand. I am doing the same ugly thing.
I do not like the check for
if (err.errors && err.status)
cause it does not identify your middleware very well.
As a first step, it would be great if we can identify error from this middleware more precisely.
Agreed.
Also, this is a duplicate of https://github.com/cdimascio/express-openapi-validator/issues/561 let's continue the discussion there.
A solution is proposed there i.e one which borrows a model similar to axios and others.
Looking forward to your feedback
Reopening as this request. It is a related, but different from that referenced above
I'd also be interested in an enhancement like this. The response validator middleware has an onError handler that lets you decide what to do with the error, and I think something similar could be useful for requests as well.
For example, simply logging some type of event and still allowing the request to continue. (In this use case, we are updating an old api that previously did not have an openapi spec and think some older clients in the wild might not conform to the spec exactly)