Skip request handler and directly pass error to first error handler
I have this piece of code
const express = require('express')
const app = express()
const { buildCheckFunction, validationResult } = require('express-validator/check');
const checkQuery = buildCheckFunction(['query']);
app.get('/', [ checkQuery('id').isUUID() ], (req, res) => {
const errors = validationResult(req);
console.log(errors.array());
res.send('')
})
app.listen(3000, () => console.log('Example app listening on port 3000!'))
Right now I always get inside my handler and have to manually check for errors, I want to directly pass the execution to my first error handler and have display the error there, without entering my request callback.
Im looking for something similar, the checkQuery could return the error directly and I dont need to call validationResult in my last function
Im looking for something similar, the checkQuery could return the error directly and I dont need to call validationResult in my last function
Here is a workaround, you can create function to take your validators as params and add a handler at the end to trigger the error handler.
const { validationResult } = require('express-validator/check');
module.exports = validators => {
if (!Array.isArray(validators)) {
validators = [validators];
}
const validationHandler = (req, res, next) => {
const errors = validationResult(req).array();
if (errors.length) {
const err = new Error('Validation failed');
err.validationErrors = errors;
return next(err);
}
next();
}
return [ ...validators, validationHandler];
}
Yes. Please go with this solution for now. express-validator doesn't have any built-in way to respond to the requests for you yet.
are there any plans to implement this in the future? something like this would be great:
router.delete(
'/',
authenticate,
query('id').isInt({ min: 1 }).toInt().return(400), //this should send a response with code 400 and the error list
checkIdExistInDb, //this will not run if id is undefined or < 1
(req, res) => {
//here I can be sure the id is valid and the user can be deleted safely
}
);
@fedeci a wrapper for something like this could be pretty simple, wdyt?
(req, res, next) => {
validationResult(req).throw();
next();
}