A request fails but your Express error-handling middleware never runs. How do you work out why?
An Express error handler is skipped when it is not registered after routes, lacks the four-argument signature, or an async error never reaches next(). Express 4 needs explicit next(err) for rejected promises; Express 5 forwards them automatically.
Answer
Short answer
If Express error middleware is not catching errors, check three things: it must have four parameters (err, req, res, next), it must be registered after the routes, and async failures must be passed to next(err) in Express 4. Express 5 forwards rejected async handlers, but ordering and signature still matter.
Mention error handling where it changes the risk, the owner, or the next check.
Was this answer helpful?
Likely follow-ups
- What happens if you call next(err) after the response has already been sent?
- How would you shape a single error handler so it returns JSON to API clients and a page to browsers?
- Where does an error thrown inside a stream's data callback end up?
- How does Nest's exception filter model differ from Express error middleware?
Related questions
- Your logs are full of Cannot set headers after they are sent. Walk me through how a request gets into that state.mediumAlso on express and error-handling4 min
- Walk me through the middleware chain of an Express service. What has to come before what, and why?mediumAlso on express and middleware4 min
- A promise rejects and nothing is awaiting it. What does Node do?hardAlso on error-handling and nodejs4 min
- Your Node service has low CPU but latency spikes for every request at the same moment. What is happening?mediumAlso on nodejs4 min