1

I'm facing a weird issue in an Express app: No error is thrown, when trying to get a property of a non existing object.

I have a file, with this code:

const bcrypt = require('bcrypt-nodejs');

const hashPassword = async (password) => {

   const bcryptGenSalt = util.promisify(bcrypt.genSalt);
   const bcryptHash = util.promisify(bcrypt.hash);

    try {
        const salt = await bcryptGenSalt(10);
        const hash = await bcryptHash(password, salt, null)

        return hash;

    } catch (error) {      
        throw error;
    }


}

module.exports = {
    hashPassword
}

As you can see, i forgot to require the "util" module of nodejs. using util.promisify should throw an error "cannot call promisify of undefined", or something like it. But nothing happens. This of course changes if i put the util.promisify call inside the try-catch block, but from what i understand, it should throw an error as it is now.

This is the code that consumes this function, in a different file(a controller):

const registerNewUser = async (req, res, next) => {  

const email = req.body.email;
const password = req.body.password;

try {
    console.log('before trying to hash')
    //THIS IS WHERE I AWAIT THE PROMISE RETURNED FROM THE "PROBLEMATIC" FUNCTION  
    var hashedPassword = await hashPassword(password)     
} catch (error) {
    return res.send({ error });
}


const user = new User({
    email,
    password:hashedPassword
})

try {

    const newUser = await user.save();
    res.json({
        error: null,
        data: {
            id: newUser._id
        }
    })
} catch (error) {
    res.status(422).send({ error: 'Email already taken' });       
}

}

The error doesn't reach the catch block, and the program keeps running, resulting undesired behavior. Can somebody explain what's going on here?

SOLVED: The problem was that for some reason, i was receiving an empty error in my postman response, making me think that no error was caught. It seems that everything works fine, besides the fact that the error object isn't being treated correctly when i do res.send({ error })...

i.brod
  • 3,993
  • 11
  • 38
  • 74
  • Error handling should work as you expect. It's not evident that `hashPassword` is called at all. Did you debug the code to be sure which line was executed and which one wasn't? How did you do this? – Estus Flask Nov 12 '18 at 18:02
  • I've updated the code, putting the entire upper function. As u can see, i have a console.log statement "before trying to hash". It's always being invoked, so there is no problem of this code not being executed. – i.brod Nov 12 '18 at 18:13
  • Possible duplicate of [this](https://stackoverflow.com/questions/17552982/nodejs-util-is-global-sometimes) Try adding `'use strict'` on the top of the files to see if a global util variable leaked. – lependu Nov 12 '18 at 18:30

0 Answers0