Express basics · core
Error handling in Express 4 and 5
Express sends errors to error-handling middleware, the functions with four parameters (err, req, res, next) registered after all routes; in Express 5 a rejected promise from an async handler is forwarded there automatically, which Express 4 did not do.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- A synchronous throw in a handler is caught by Express. In Express 5 a rejected promise (an async handler that throws) calls next(err) automatically. In Express 4 async errors were lost as unhandled rejections unless you wrapped handlers or used express-async-errors.
- Errors thrown inside callbacks or timers are not caught: call next(err) yourself.
- Express recognises error middleware by its arity: exactly four parameters. Register it last. You can chain several (log, then respond).
- If headers are already sent (for example while streaming), call next(err) so Express's default handler closes the connection.
- Use one error format for the whole API (e.g. RFC 9457 problem details). Map known error classes (validation -> 400, not found -> 404, conflict -> 409); unknown errors -> 500 with a generic message and full details only in the logs.
- The default handler uses err.status or err.statusCode, and shows the stack only when NODE_ENV is not 'production'.
- A 404 is not an error in Express: add a normal middleware after all routes to send it.
The red pen
Common traps: mistake → fix
Mistake: Express 4 catches errors from async handlers
Fix: only Express 5 does; Express 4 needs a wrapper.
Mistake: (err, req, res) with three parameters is an error handler
Fix: Express checks for four; keep next even if unused.
Mistake: Send err.message and err.stack to the client
Fix: that leaks internals; log them and send a safe message.
Easy to hard
Questions interviewers ask, easy to hard
- How do you handle errors in Express?
- How are async errors handled in Express 4 vs Express 5?
- How does Express know a middleware is an error handler?
- Design one error response format for a whole API.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.