How add middleware for 404 errors on express

Viewed 640

setting

app.use("/api/tobaccos", tobaccos);

app.use(function(err, req, res, next) {
  console.error(err.message);
});

api:

router.get("/:id", async (req, res) => {
  console.log("GET TOBACCO:" + req.params.id);

  await Tobacco.findById(req.params.id)
    .then(tobacco => res.status(200).json({ status: "success", data: tobacco }))
    .catch(error => res.status(404).json({
      status: "fail",
      msg: "Tobacco not found!",
      code: "error.tobaccoNotFound"
    }));

});

I'm trying to add middleware for all 404 errors

app.use(function(err, req, res, next) {
  console.error(err.message);
});

or this doesn't work

app.get('*', function(req, res){
  res.status(404).send('what???');
});

What is wrong?

2 Answers

In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})

Add routes dynamically at runtime on an instance of express.Router() so the routes are not superseded by a middleware function.

Reference: https://expressjs.com/en/starter/faq.html

You can add this middleware in your root file. It sends error for any invalid routes.

 //Handles 404 errors
app.use((req, res, next) => {
    const error = new Error('Error Occured');
    error.status = 404;
    next(error);
});
app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    });
});

Alternatively, you can try which captures all 404 errors

app.use(function(req, res, next) {
    res.status(404).send( 'Error Occured! ');
});
Related