I have this piece of code to signup a new user in NodeJS with passport as authentication middleware. The case is that I cause an error to throw an exception and thus see where and how I have to handle it, but it is not being caught. here I put an example:
passport.use('signup', new localStrategy(
{
passReqToCallback: true,
usernameField: 'email'
},
async function (req, email, password, done) {
try{
let findOrCreateUser = async function () {
let result = await userModel.findOneUser(email);
if (result != null) {
console.log("El usuario ya existe");
done(null, false);
} else {
let user = new userModel();
user.username = req.body.username;
user.email = email;
user.password = await createHash(password);
await userModel.newUser(user);
return done(null, user);
}
}
await process.nextTick(findOrCreateUser);
}catch(e){
console.log("asdasd");
done(null, false);
}
}
))
and the createHash function where I intentionally cause an error by calling the genSal function, instead of genSalt.
async function createHash(password){
try{
let salt = await bcrypt.genSal(20);
let hash = await bcrypt.hash(password, salt);
return hash;
}catch(e){
throw e;
}
}
Why don't you catch it: Unhandled exception.
Should I put the try/catch somewhere else?
Thanks in advance.
It is an interesting question, we are going to try to reproduce the scenario, building a similar code little by little.
We see that the error is not captured and therefore does not appear in the console of the fragment.
But it does appear in the browser console, we can see it by pressing F12or Ctrl+ Mays+ I.
Let's try another way, catching the promise error.
For this we'll need to use
await
(and thus create a function that I'll callmain
, since JS doesn't support usingawait
outside of an async function):If we force it to wait for the promise to execute and resolve, then it works.
But in your scenario there is something else: you are defining an async function that is passed to
process.nextTick
. ButnextTick(fn)
it is not an asynchronous function, its behavior is similar tosetTimeout(fn)
. Therefore, theawait
one you have put in front is totally ignored: