0

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.

  • Does this answer your question? [Express 4 middleware error handler not being called](https://stackoverflow.com/questions/29700005/express-4-middleware-error-handler-not-being-called) – NIKUNJ PATEL Feb 17 '23 at 10:08
  • No, I have already gone through all the possible solution. – Ayush Sachan Feb 17 '23 at 10:22

2 Answers2

0

Your custom error handler must be established after all the application stack (after the app.listen call).

Source: Express 4 middleware error handler not being called

alcan
  • 31
  • 1
  • 8
0

You can try this one:

export const getPost = (req, res, next) => {
    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) {
            // Pass the error down to the error handler middleware
            return next(new Error("Something went wrong, please try again."));
        }
        
        if (data.length == 0) {
            // Pass the error down to the error handler middleware
            return next(new Error("Invalid post id"));
        }

        return res.status(200).json(data[0]);
    });
};
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
  • 1. Not working, cannot set headers after they are sent to the client. 2. I don't want to do this in that way. I have figured out that error handler is not catching error because before the error is handled by the error handler, it is handled by MySQL library. – Ayush Sachan Feb 17 '23 at 10:30