express-validator
in my api to validate the received data, I'm creating a custom validation to check if the user's email is already registered in the system, but I can not fire a throw new Error('Email em uso');
validator since my sql query is returned in a callback function, so if I use throw new Error
it is directed to the callback function and not the main one.
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 already said, when the email already exists it triggers an error to the callback function, and since it is not surrounded by try{} catch(){}
my application to:
How can I get out of this situation and trigger an error for the main function?