Issue
I am using postman with nodejs and MySQL.
Middleware
const notFound = (req, res, next) => {
const error = new Error(`Not Found -${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === "production" ? null : err.stack,
});
};
export { notFound, errorHandler };
here I am trying to use notFound
and errorHandler
for the authUser
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select @uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT @uid := NULL) init_var where email=?;select @finaluid:= `user_id` from user_type, (SELECT @finaluid := NULL) init_var where user_id [email protected] AND type='customer';select customer_id, password from customer where user_id [email protected];";
db.query(sql, [email], (err, result) => {
if (err) throw err;
if (result) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["@finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401);
throw new Error("Invalid email or password");
}
}
} else {
res.status(401);
throw new Error("Invalid email or password");
}
});
});
Now for this particular controller, I am accessing api/users/signin
which is valid. But When I use something like api/users/signin/ksds
. It does use notFound
middleware and gives me error in postman.
But in body If I use incorrect password
, it should show error in postman console. But what it does it gives me error in vscode console. like this,
And I have to refresh the server everytime.
In order to access the notFoundand
errorHandler, I am using
app.use` in server.js like this,
app.use(notFound);
app.use(errorHandler);
How can I solve this? So, that this will help me in showing error in the frontend too.
Solution
This errors comes in when you get empty results. You should first check the length of the results then use properties or index on it.
const authUser = asyncHandler(async (req, res) => {
const { email, password } = req.body;
let sql =
"select @uid :=`user_id`, first_name, last_name, email from dasa_user as var, (SELECT @uid := NULL) init_var where email=?;select @finaluid:= `user_id` from user_type, (SELECT @finaluid := NULL) init_var where user_id [email protected] AND type='customer';select customer_id, password from customer where user_id [email protected];";
db.query(sql, [email], (err, result) => {
try {
if (err) throw err;
if (result.length > 0) {
if (result[2][0] == null) {
res.status(401);
throw new Error("user not Found");
} else {
if (MatchPassword(password, result[2]["0"]["password"])) {
res.json({
first_name: result[0][0]["first_name"],
last_name: result[0][0]["last_name"],
email: result[0][0]["email"],
userId: result[1]["0"]["@finaluid:= `user_id`"],
customerId: result[2]["0"]["customer_id"],
password: result[2]["0"]["password"],
token: generateToken(result[0][0]["email"]),
});
} else {
res.status(401); // this else is calling up for (If you use incorrect password)
throw new Error("Invalid email or password");
}
}
} else {
res.status(401).send({message: 'Results not found'}); // change this to send error message to the frontend, you can really customise it based on your needs.
// throw new Error("Results not found"); // Now this error is thrown because you don't have results
}
} catch (error) {
console.error(e);
}
});
});
But When I use something like api/users/signin/ksds. It does use
notFound middleware and gives me error in postman.
Because you are creating a custom error and sending it to node default error handler which does the work for you and postman receives the error message.
But in body If I use incorrect password, it should show error in
postman console. But what it does it gives me error in vscode console
However, in this case your are throwing an error and it is doing its job and you see that error in the console. If you don’t want this behaviour follow the same flow as used above.
Check for more details: How to handle errors in Node.js?