1
I’m using the express-validator
in my api to validate the received data, I am creating a custom validation to verify that the user’s email is already registered in the system however, I can’t fire a throw new Error('Email em uso');
for the main function of the express-Validator since my sql query is returned in a callback function, so if I use the throw new Error
it is directed to callback function and not to the main.
My code:
app.post('/account/new/validate', [
body('emailRegistro')
.isLength({ min: 5, max: 50 })
.isEmail()
.custom((emailRegistro) => {
accountModel.VerificarEmailExistente(sql, emailRegistro, (error, result) => {
console.log("Chegou aqui - 1");
if(result.length !== 0){
console.log("Chegou aqui - 2");
throw new Error('Email em uso'); //Erro disparado a função de callback do sql.query, esse erro precisa ir para a função principal
return;
}
});
})
.withMessage('Email Inválido')
], (req, res, next) => {
try{
validationResult(req).throw();
//Validações concluídas
console.log("OK");
}catch(err){
//Retorno dos erros de validação
return res.json({ errors: err.mapped() });
}
});
As I said, when the email already exists it triggers an error to the callback function, and as it is not surrounded by try{} catch(){}
my application to:
How can I get out of this situation and trigger an error to the main function?