I'm modifying the Error handling of the Express-Validator middleware to go through my custom Error Handling middleware but the message of the validationResult resolves to [object Object].
Express-Validator error handling
const expressValidationError = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const err = new Error(errors.array());
err.status = 400;
next(err);
} else {
next();
}
};
Express Error Handling middleware
app.use((err, req, res, next) => {
const status = err.status || 500;
res.status(status).json({
error: {
status: status,
message: err.message || "Internal Server Error",
},
});
});
This is the result of the error object which is returned from validationResult:
Result {
formatter: [Function: formatter],
errors: [
{
value: 'b',
msg: 'Username Must be Between 5 to 255 Characters Long!',
param: 'username',
location: 'body'
}
]
}
And this is the errors.array():
[
{
value: 'b',
msg: 'Username Must be Between 5 to 255 Characters Long!',
param: 'username',
location: 'body'
}
]
I know that I can just use res.status(400).json({ error: errors.array() }); in the Express-Validator and avoid all these but I would prefer if it was passed to next() and handled by the error middleware.
Is there any way to do so or should I just go with the other way?