I'm trying to use a custom error handler for my express application, but it is not getting called.
I have added an error handler at the bottom of index.js file
app.use("/api/auth", authRoutes);
app.use(errorHandler);
app.listen(process.env.PORT, () => {
console.log("Server stared sucessfully at port " + process.env.PORT);
});
errorHandler.js
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
res.status(statusCode).json({
message: err.message,
});
next();
};
export default errorHandler;
In the controllers directory, postController.js
export const getPost = (req, res) => {
const q =
"SELECT posts.id, `username`, `title`, `desc`, posts.img, users.img AS userImg, `category`, `date` FROM users JOIN posts on users.id = posts.uid WHERE posts.id = ?";
db.query(q, [req.params.id], (err, data) => {
if (err) {
res.status(500);
throw new Error("Something went wrong, please try again.");
}
// Error handler is not catching this error and my application crashes every time.
if (data.length == 0) throw new Error("Invalid post id");
return res.status(200).json(data[0]);
});
};
Console
Server stared sucessfully at port 8080
file:///E:/Programming/Web/Blog/backend/controllers/postController.js:39
if (data.length == 0) throw new Error("Invalid post id");
^
Error: Invalid post id
at Query.onResult (file:///E:/Programming/Web/Blog/backend/controllers/postController.js:39:37)
at E:\Programming\Web\Blog\backend\node_modules\mysql2\lib\commands\query.js:86:16
at processTicksAndRejections (internal/process/task_queues.js:77:11)
[nodemon] app crashed - waiting for file changes before starting...
Edit: If I throw an error outside the callback function, it is getting handled by the handler. I think it is happening because before the error is handled by handler, it is handled by the MySQL library. Please correct me Im wrong.