Search code examples
node.jsexpressmongoosees6-promise

Error in Promise Not sending any error in response object in NodeJS/Express/Mongoose


I am trying to convert old mongoose promise code to Native ES6 Promise. I am getting all the errors thrown in catch and I can log it in console but when I try to pass it to response object I get empty object. Following is my code

module.exports.login = function(req, res) {

    var userPromise = User.findOne({email:req.body.email}).exec();

    userPromise.then(function(user) {
        if(!user){
            throw new Error("step 1 failed!");
        }
    })
    .then(function(user) {
        if(!user.comparePassword(req.body.password)){
            throw new Error("step 2 failed!");
        }else {
            return res.json({token: jwt.sign({email:user.email, name:user.name, _id: user._id}, 'SOMETOKEN')});

        }
    })
    .catch(function(err) {
        console.log('Error: '+err);
        return res.status(401).send(err);       

    });
};

Please do let me know if I am on a right path or am I doing some mistake over here. Thanks in advance.


Solution

  • An Error instance is an object, and Express will (AFAIK) use code similar to this:

    res.status(401).send(JSON.stringify(err))
    

    The result of JSON.stringify(err) is {} because its main properties (name, message and stack) are not enumerable.

    I'm not sure what exactly you want to return to the user, but it's common to send back the message property of that object:

    return res.status(401).send({ error : err.message });
    

    Also, your second .then() is superfluous, you can shorten your code to this:

    userPromise.then(function(user) {
      if (! user) {
        throw new Error("step 1 failed!");
      }
      if (! user.comparePassword(req.body.password)) {
        throw new Error("step 2 failed!");
      }
      return res.json({token: jwt.sign({email:user.email, name:user.name, _id: user._id}, 'SOMETOKEN')});
    }).catch(function(err) {
      return res.status(401).send({ error : err.message });
    });