How should Express handle errors?
Try code in the playgroundUnderstand 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:
// 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.
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.
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.
Adapted from 02_NODE_EXPRESS_HTTP.md · “How should Express handle errors?”. Examples are study fragments; framework behavior can depend on your version.