CodePark/ questions / HTTP servers & Express middleware
START PRACTICINGPRACTICE
Backend question · Node.js › HTTP servers & Express middleware

db.find rejects. What happens in Express 4 compared with Express 5?

app.get("/users/:id", async (req, res) => {
  const user = await db.find(req.params.id);
  res.json(user);
});

app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});
Express 4 does not catch the rejection, so the error handler never runs and the rejection is unhandled; Express 5 forwards it to the error handler

Express 4 does not catch the rejection, but Express 5 forwards it to the error handler.

Express 4 calls the handler and ignores the promise it returns. So the rejection becomes
unhandled: nothing catches it. No response is sent. On Node 15 and later, an unhandled rejection crashes the process by default. In Express 4, you had two fixes:
• Wrap each handler in
try/catch and call next(err).
• Use a helper package like
express-async-errors.

Express 5 checks the returned promise. If it rejects, Express 5 calls
next(err) for you. So "Both versions pass the error to the error handler" is wrong for Express 4.