Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialPoJung Chen
5,856 PointsWhen will "user not found" error in user.js been shown?
In the model of user.js, I wrote the code below:
UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ email: email })
.exec(function (error, user) {
if (error) {
return callback(error)
} else if (!user) {
var err = new Error('User not found')
err.status = 401
return callback(err)
} else {
bcrypt.compare(password, user.password, function (error, result) {
if (error) {
return callback(error)
} else if (result === true) {
return callback(null, user)
} else {
return callback()
}
})
}
})
}
My question is when will the 'User not found'
error been executed ??
Because after I type the wrong email in login form, it always send back 'Wrong email or password'
error in routes of index.js.
2 Answers
Montazar Al-Jaber
19,611 PointsIt is there, but you have to output it. It is available in the error object that we return from the authenticate method.
user.authenticate(req.body.email, req.body.password, function(error, user) {
if (error || !user) {
const err = new Error('Wrong email or password');
console.log(error.message); // 'User not found'
}
});
Enter a non-existing or incorrect credential and look at the Console. You'll find the message there. Once again, the teacher did not make use of this object. Perhaps, it has something to do with Node's callback pattern, where data (or arguments) are always preceded by an error object.
David Lacho
20,864 PointsThe issue seems to be that whether or not a user is created, all login errors are displaying "Wrong email or password." As Muntazir pointed out, for some reason the teacher did not make use of the error object that is found in the returned callback from the User schema. I was able to display the correct message by adding another conditional statement that checks first if an error is returned from the callback:
if (error || !user) {
if (error) {
return next(error);
} else {
const err = new Error("Wrong email or password");
err.status = 401;
return next(err);
}
}