ExpressInterview preparation
Intermediate·Concept·2 min read

How should Express handle errors?

Practice this question

Definition:

Error handling turns application failures into predictable responses and useful internal logs. Express uses error middleware with four arguments to handle errors passed into its request pipeline. Synchronous throws are handled by Express, while promise forwarding differs between Express 4 and 5.

Key points:

  • Add error middleware after routes: (err, req, res, next).
  • Express 5 forwards rejected returned promises; Express 4 needs explicit forwarding for async errors.
  • Log useful context and return a safe message without stack traces.

Reference: Express error handling.

  • Return after sending an error response, and delegate with next(err) if headers have already been sent.

Example — forwarding an async error in Express 4 or 5:

JavaScript
// Inside a configured Express app; loadUser is the app's service.
app.get('/users/:id', async (req, res, next) => {
  try {
    const user = await loadUser(req.params.id);
    if (!user) return res.status(404).json({ message: 'User not found' });
    return res.json(user);
  } catch (error) {
    next(error);
  }
});

app.use((error, req, res, next) => {
  if (res.headersSent) return next(error);
  res.status(500).json({ message: 'Something went wrong' });
});
  • This shows error forwarding only; production code also needs request validation, access checks and safe internal logging.

Interview point:

  • Expected failures such as validation errors should have suitable client-facing status codes; unexpected failures should not reveal internal details.
Adapted from 02_NODE_EXPRESS_HTTP.md · “How should Express handle errors?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.