validateRequest middleware: Cleaner validation message
I'm currently using swagger-express-middleware package to validate the requests against my Swagger API document.
Following your document, I have implemented the middleware and handled the error as shown below
createMiddleware(swaggerDoc, app, (middlewareError, middleware) => {
app.use(middleware.metadata());
app.use(middleware.parseRequest());
app.use(middleware.validateRequest());
// Error handler to send the swagger validation response
app.use((err, req, res, next) => {
res.status(err.status).json({
type: 'SCHEMA VALIDATION FAILED',
message: err.message
});
});
});
If any error in the schema, the response I get back from the middleware has a property message with description of the error which is obviously an important part of the response as it tells the requester whats missing. Unfortunately though, the message content is not very intuitive or readable. For example if a property is missing from the request the description would be
"message": "The \"pinDetails\" body parameter is invalid ({\"Pindd\":\"asd\"}) \nJSON Schema validation error. \nData path: \"\" \nSchema path: \"/required/0\" \nMissing required property: pin"
As you can see the message is not very intuitive and clean which makes it hard to read. So, my question is, does the package provide any way to get back a cleaner version of the message or any other way I can do the same ?
Note: Since the message is multi-line and most importantly dynamic, I cant just split or replace the strings or it would look like some unrelated sentences put together (maybe worse case that's what I would do ultimately but definitely not what I would prefer).
Yeah, I agree that the error messages aren't very user-friendly or easy to parse. The errors ultimately come from tv4, which is the JSON Schema validator that I use under the hood. TV4 adds a few helpful properties to its Error objects, such as dataPath and schemaPath, which may help you construct a more user-friendly message. In the future, I plan to switch to Z-Schema, which has better error messages and adds much more helpful properties to the Error objects, which makes it much easier to construct user-friendly messages.