Error in Promise Not sending any error in response object in NodeJS/Express/Mongoose
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 });});
Add return Promise.resolve(user)
at the end of your first then()
block.