Hi Everyone
So, in order to learn node.js and express, I’m following along with this course on the FCC youtube channel, and I wanted to clarify something on the Express error handling.
In the express docs, an “error handler” in Express is a midware that has four parameters:
Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the
next
object, you must specify it to maintain the signature. Otherwise, thenext
object will be interpreted as regular middleware and will fail to handle errors.
In the above course, the instructor (John Smilga) creates two error handlers, one is a general error-handler, and the other a “not found” error handler. This is the first one, with four params as per the docs:
const errorHandlerMiddleware = async (err, req, res, next) => {
console.log(err)
return res.status(500).json({ msg: 'Something went wrong, please try again' })
}
However, this is the “not found” error handler - only two params (three, with next() omitted):
const notFoundMidware = (req, res) => {
return res.status(404).json({ msg: "Products Not found." });
};
And this works, whenever a product isn’t found. More than that - when I rewrote it with four params, to make it similar to the Error-Handler above, it didn’t work. It only works as a regular router, though it’s supposed to be an error handler.
This is seems very weird. Could anyone please clarify?
This is how the midwares are mounted in my app.js:
app.get("/", (req, res) => {
return res.status(200).send(`<h1>Store API</h1><a href="/api/v1/products">Products Page</a>`);
});
app.use("/api/v1/products", prodRouter);
//Middleware
app.use(express.json());
app.use(errorHandlerMiddleware);
app.use(notFoundMidware);