Issue with throwing error

there is something confusing here in express how i got 200 response in the both cases if i find a book or not this is the error handler middleware
const errorhandler = (err, req, res, next) => {
console.log(res.statusCode);
const statusCode = res.statusCode ? res.statusCode : 500;

switch (statusCode) {
case 400:
return res.status(400).json({
title: "Validation failed",
message: err.message,
stackTrace: err.stack,
});
case 401:
return res.status(401).json({
title: "Not Authorized",
message: err.message,
stackTrace: err.stack,
});
case 403:
return res.status(403).json({
title: "Forbidden",
message: err.message,
stackTrace: err.stack,
});
case 404:
return res.status(404).json({
title: "Not Found",
message: err.message,
stackTrace: err.stack,
});
default:
console.log("No errors");
break;
}
res.json();
};

module.exports = errorhandler;
const errorhandler = (err, req, res, next) => {
console.log(res.statusCode);
const statusCode = res.statusCode ? res.statusCode : 500;

switch (statusCode) {
case 400:
return res.status(400).json({
title: "Validation failed",
message: err.message,
stackTrace: err.stack,
});
case 401:
return res.status(401).json({
title: "Not Authorized",
message: err.message,
stackTrace: err.stack,
});
case 403:
return res.status(403).json({
title: "Forbidden",
message: err.message,
stackTrace: err.stack,
});
case 404:
return res.status(404).json({
title: "Not Found",
message: err.message,
stackTrace: err.stack,
});
default:
console.log("No errors");
break;
}
res.json();
};

module.exports = errorhandler;
and this is the function
const updateBook = asyncHandler(async (req, res) => {
const book = await Books.findById(req.params.bookId);
if (!book) {
res.status(404); // Set the response status to 404
throw new Error("Book not found");
} else {
res.status(200).json(book);
}
});
const updateBook = asyncHandler(async (req, res) => {
const book = await Books.findById(req.params.bookId);
if (!book) {
res.status(404); // Set the response status to 404
throw new Error("Book not found");
} else {
res.status(200).json(book);
}
});
No description
No description
34 Replies
Jochem
Jochem14mo ago
I'm not super familiar with express or its middleware, but
const statusCode = res.statusCode ? res.statusCode : 500;
const statusCode = res.statusCode ? res.statusCode : 500;
Are you sure you want to use res.statusCode? https://expressjs.com/en/4x/api.html#res This seems to suggest res doesn't have a statusCode property that would mean the statusCode variable would be 500, which is a case you're not handling (also, you can write that as const statusCode = res.statusCode ?? 500; instead of having res.statusCode twice) hm, wait, it does log out the 200 doesn't it. Maybe Books.findById is returning something truthy even if it doesn't find anything? What ORM are you using?
MuhammedAlaa
MuhammedAlaa14mo ago
yep that what i was going to tell you that it logs out 200 when it goes to the error handler im using mongoose
Jochem
Jochem14mo ago
seems like you need to call exec() on findById https://mongoosejs.com/docs/api/model.html#Model.findById()
await Adventure.findById(id).exec();
await Adventure.findById(id).exec();
which would return null, which is falsey, so it should work as expected
MuhammedAlaa
MuhammedAlaa14mo ago
same issue i tried to log the result from the findById it doesn't log any thing if not found
MuhammedAlaa
MuhammedAlaa14mo ago
const updateBook = asyncHandler(async (req, res) => {
const book = await Books.findById(req.params.bookId).exec();
console.log(book);
if (!book) {
res.status(404); // Set the response status to 404
throw new Error("Book not found");
} else {
res.status(200).json(book);
}
});
const updateBook = asyncHandler(async (req, res) => {
const book = await Books.findById(req.params.bookId).exec();
console.log(book);
if (!book) {
res.status(404); // Set the response status to 404
throw new Error("Book not found");
} else {
res.status(200).json(book);
}
});
No description
No description
Jochem
Jochem14mo ago
can you change it to console.log(typeof book);?
MuhammedAlaa
MuhammedAlaa14mo ago
if found => object not found doesn't log anything
Jochem
Jochem14mo ago
that is very strange, even if it is returning null it should still log out something, in both situations btw with the ID that should 404, is it still matching with this route?
MuhammedAlaa
MuhammedAlaa14mo ago
but it goes inside the if because if it didn't then it will not log the res.statusCode
Jochem
Jochem14mo ago
that's in the middleware though
MuhammedAlaa
MuhammedAlaa14mo ago
idk how it goes inside the if and still response with 200
Jochem
Jochem14mo ago
it looks like the 404 isn't hitting updateBook at all, otherwise you'd see the log and have an error thrown, I see none of those in the console add a console.log above findById that just logs out something like "in updateBook"
MuhammedAlaa
MuhammedAlaa14mo ago
No description
Jochem
Jochem14mo ago
hm, that is very strange I'm honestly not sure what's causing that then
MuhammedAlaa
MuhammedAlaa14mo ago
np appreciate your help i will try to figure it out or look for a tutorial doing the same thing
Jochem
Jochem14mo ago
Hopefully someone else will come along that does know 🙂 good luck!
MuhammedAlaa
MuhammedAlaa14mo ago
i tried to put my code in a try catch block and it worked fine idk why i can't figure out
const updateBook = asyncHandler(async (req, res) => {
try {
const book = await Books.findById(req.params.bookId);
console.log(book);
res.status(200).json(book);
} catch (error) {
console.log(error);
res.status(404); // Set the response status to 404
throw new Error("Book not found");
}
});
const updateBook = asyncHandler(async (req, res) => {
try {
const book = await Books.findById(req.params.bookId);
console.log(book);
res.status(200).json(book);
} catch (error) {
console.log(error);
res.status(404); // Set the response status to 404
throw new Error("Book not found");
}
});
No description
Jochem
Jochem14mo ago
hm, the docs for mongoose claim it just returns null when it can't find the book, but I guess it's throwing after all good to know you found a solution though!
MuhammedAlaa
MuhammedAlaa14mo ago
yep im just wondering how , i found a tutorial doing what i did exactly and works fine maybe something is new in moongose idk
Jochem
Jochem14mo ago
yeah, could be a version issue
MuhammedAlaa
MuhammedAlaa14mo ago
yep, any ways thanks for your time ❤️
ErickO
ErickO14mo ago
haha, timezones I would've told you this right away cause been there done that always been that way, if you look for 1 thing and it's not there it throws
Jochem
Jochem14mo ago
stupid, lying docs 😄
ErickO
ErickO14mo ago
only time when it doesn't throw is if you look for more than one thing findMany and it's not there because ofc it does consistency
Jochem
Jochem14mo ago
another good reason I usually prefer just a DB driver over a ORM
ErickO
ErickO14mo ago
haha funny you should mention that that's just mongo same thing happens in Go so I'm guessing is how mongo works so...another good reason to not use mongo 😎
Jochem
Jochem14mo ago
haha, well, nice to see I can just move the column over without changing its header ;D
ErickO
ErickO14mo ago
reason why I hate this so much is that now you have to consider the error if you want to do something specific in each case, because sure any error you can send a 404 but it isn't always a not found error...so if you wanted to show different messages you now have to check what error it is to send either a 404 or a 500
MuhammedAlaa
MuhammedAlaa14mo ago
ok i got u but still can't know why it doesn't log book when its not found ?
Jochem
Jochem14mo ago
because throwing an error stops code execution in the current context
MuhammedAlaa
MuhammedAlaa14mo ago
hmm, but the log was before even checking if there is book or not ok maybe because asynchandler of express resolve the await directly and throw the error ?
Jochem
Jochem14mo ago
hm, I'm not sure
MuhammedAlaa
MuhammedAlaa14mo ago
https://www.npmjs.com/package/express-async-handler i think because it take a look here
npm
express-async-handler
Express Error Handler for Async Functions. Latest version: 1.2.0, last published: 2 years ago. Start using express-async-handler in your project by running npm i express-async-handler. There are 201 other projects in the npm registry using express-async-handler.
MuhammedAlaa
MuhammedAlaa14mo ago
asyncHandler catches the error automatically i think because of this it doesn't log
Want results from more Discord servers?
Add your server