LESSON 02 / 2·2 min readIntermediate

How should Express handle errors?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

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.

Important ideas

  • 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.
PAUSE & RECALL

Can you explain it without the notes?

How should Express handle errors?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

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.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Expected failures such as validation errors should have suitable client-facing status codes; unexpected failures should not reveal internal details.
Practice this concept
YOUR NEXT STEP

You’ve reached the end of this guide.

Prepare for Express interviews

Adapted from 02_NODE_EXPRESS_HTTP.md · “How should Express handle errors?”. Examples are study fragments; framework behavior can depend on your version.