express-validator icon indicating copy to clipboard operation
express-validator copied to clipboard

Skip request handler and directly pass error to first error handler

Open nikksan opened this issue 7 years ago • 5 comments

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.

nikksan avatar Sep 01 '18 17:09 nikksan

Im looking for something similar, the checkQuery could return the error directly and I dont need to call validationResult in my last function

lehno avatar Sep 18 '18 16:09 lehno

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];
}

nikksan avatar Sep 25 '18 20:09 nikksan

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.

gustavohenke avatar Oct 01 '18 13:10 gustavohenke

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
    }
);

mugi-luffy avatar Jan 19 '22 14:01 mugi-luffy

@fedeci a wrapper for something like this could be pretty simple, wdyt?

(req, res, next) => {
	validationResult(req).throw();
	next();
}

gustavohenke avatar Jan 22 '22 12:01 gustavohenke