this is my first post on Stackoverflow, so please be kind.
I have a huge problem, which I couldn't fix by googling (which is pretty rare). I want to create a simple error handling in my query, but it won't work.
Here's the code:
pool.query("SELECT password_hash FROM User WHERE email = ?",
req.body.EMailLogin, (error, results, fields) => {
if(error) {
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function(err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);
CodePudding user response:
You need to throw the err inside the if
if(error) {
throw error;
} else {
And I think that the error is how you're passing the parameter, it should be an array:
pool.query("SELECT password_hash FROM User WHERE email = ?",
[req.body.EMailLogin],
I hope this fixes your problem.
CodePudding user response:
You missed to check weather query return data or not and also you can pass values either using object or array(in your case, should be array)
pool.query("SELECT password_hash FROM User WHERE email = ?", [req.body.EMailLogin],
(error, results, fields) => {
if (error) {
// any error like wrong query, connection closed, etc.
// It executes the if aswell as the else statement and I dont know why (if(error) seems to be ignored even if its true)
} else if (results.length === 0) {
// email not found in database
// My Page for Wrong Email ???
} else {
// And then it crashes here, because password_hash is undefined
let hash = results[0].password_hash;
bcrypt.compare(req.body.PasswordLogin, hash, function (err, result) {
if (result == true) {
ses.user = req.body.EMailLogin;
req.session.cookie.expires = false;
req.session.save(() => {
return res.redirect('/index');
});
} else {
res.render(); // My Page for Wrong Password (ignore this)
}
});
}
}
);