I have the following function for handling a user registration in node.js v8.9:
module.exports = async (req,res) =>{
const User = req.app.locals.User;
const user =User.build({
email: req.body.email,
displayName: req.body.display_name,
realName: req.body.real_name,
hashedPassword:req.body.password ,
role: 0
});
try{
await user.save();
res.send({message:"Usuario creado exitosamente.", success:true });
}
catch(ex)
{
res.send({message:"Información es inválida:", success:false});
}
res.end();
};
As you can see I am using async and await for handling when the user does not create successfully. However, my catch() never executes when creation fails. Why? Is there a different way to handle promise rejections with async/await? Someone suggested using thow new Error(), but I don't want to throw an error, I just want to send a message back to the client.
More background info: the app is made with Express.js, and using Sequelize.js as an ORM. I have saved my User model into req.app.locals to that I have access to it from my route handlers. The datatable, actually saving into MS SQL Server, has a UNIQUE constraint on the email column, to a User registering with an already existing e-mail would cause the user.save() promise to fail.
When testing, in the console, I see the exception from sequelize.js saying that the UNIQUE constraint did not allow the record creation. However, my catch statement does not get executed and the client (in this case the browser), remains waiting for a response until it times out. If I change the async/await to use .then()
and .catch()
it works correctly (no try/catch block needed, either).