I have an Express.js app in which I'm trying to log the validation errors returned by Celebrate to the console so that I can analyze them with the logging service that I use (which is GCP's Cloud Logging).
I'm currently just using the error handling middleware provided by Celebrate as suggested in the documentation:
// app.js
const { errors } = require('celebrate');
...
app.use(errors());
...
How can I extend the middleware (without re-implementing it) so that it also logs the validation errors to the console?
The simplest way to achieve this seems to be by defining another error middleware before the Celebrate error middleware, that checks whether the error is a Celebrate error (using the isCelebrateError
method) and if so it logs it to the console:
// app.js
const { errors, isCelebrateError } = require('celebrate');
...
// middleware to log Celebrate validation errors
app.use((err, req, res, next) => {
if (isCelebrateError(err)) {
console.error(err);
}
next(err);
});
// Celebrate middleware to return validation errors
app.use(errors());
...
It is important to include the logging middleware before Celebrate's errors()
middleware since errors()
returns a JSON response and no other middleware is run after it (you can check out the Celebrate source code for the implementation details of errors()
).