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

江枫思渺然 提交于 2021-02-10 14:23:40

问题


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.


回答1:


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 });
});



回答2:


Add return Promise.resolve(user) at the end of your first then() block.



来源:https://stackoverflow.com/questions/44152189/error-in-promise-not-sending-any-error-in-response-object-in-nodejs-express-mong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!