Home > OS >  Why this express middleware error handling is not working?
Why this express middleware error handling is not working?

Time:12-11

I am doing some error handling for the express globally. when I follow the documentation from this link Express

its was written in something lie this

app.use((err, req, res, next) => {
  console.log(req.originalUrl);
  next()
})

The thing is that when i try to accept 4 variables inside the function. Its doesn't works.

But when I try to convert the above into something like this without err

app.use(( req, res, next) => {
      console.log(req.originalUrl);
      next()
   })

it start working and its show me the console.log So What is wrong here?

Here is my server code file

const app = express();

app.use((err, req, res, next) => {
  console.log(req.originalUrl);
  next()
})


app.get("/", (req, res) => {
  res.send("api running");
});

const PORT = process.env.PORT || 5000;

app.listen(
  PORT,
  console.log(
    `server running ${process.env.NODE_ENV} on port ${PORT}`
  )
);

I am using these versions

"express": "^4.17.1", "mongoose": "^6.1.0"

CodePudding user response:

From the documentation you pointed to:

You define error-handling middleware last, after other app.use() and routes calls

And you are not doing that, you are defining it before your other routes. Move it to the end of the list and it should work.

const app = express();

app.get("/", (req, res) => {
  res.send("api running");
});

app.use((err, req, res, next) => {
  console.log(req.originalUrl);
  next()
})

const PORT = process.env.PORT || 5000;

app.listen(
  PORT,
  console.log(
    `server running ${process.env.NODE_ENV} on port ${PORT}`
  )
);

CodePudding user response:

A four variable middleware is ONLY invoked when there's an actual error. It is not executed until either something calls next(err) or no request handler handles the request and it gets to the end of Express' routing and it looks for default error handlers.

Also, make sure your error handling middleware is registered last.


If you want middleware to be executed on all requests, then just declared it with the usual three variables and it will be called as a regular middleware if the request is routed to it. This is an Express design requirement (kind of an odd design, but it is the way it is).

So, your design intent is EITHER to register an error handling middleware (that is executed only in error conditions) or a regular middleware (that is executed on normal requests). You have to decide which you want. If you want both, then implement two separate handlers, one with the three arguments and one with four.

  • Related