How to handle errors in Express applications
· Category: Node.js
Short answer
Define an error-handling middleware with four arguments (err, req, res, next) at the end of your middleware stack to catch and respond to errors centrally.
Steps
- Create a custom error class or use the built-in Error object.
- In route handlers, pass errors to
next(err)to trigger error middleware. - Define error middleware last:
app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });. - For async handlers, wrap them in a utility that catches rejected promises and calls
next(err). - Log errors before sending responses to aid debugging.
Tips
- Use a library like
express-async-handlerto avoid repetitive try/catch blocks in async routes. - Never leak stack traces or internal details to clients in production; log them server-side instead.
Common issues
- Error middleware must have exactly four parameters, or Express treats it as regular middleware.
- Unhandled promise rejections in async routes can crash the server unless properly caught.