How to Create Error Handling Middleware in Express
In Express, create error handling middleware by defining a function with four parameters:
err, req, res, next. Place this middleware after all other routes to catch errors and send proper responses.Syntax
Error handling middleware in Express has a special signature with four parameters: err, req, res, and next. Express recognizes it by the first err parameter.
This middleware catches errors passed via next(err) or thrown in routes.
javascript
function errorHandler(err, req, res, next) { res.status(500).send({ error: err.message }); }
Example
This example shows a simple Express app with an error handling middleware that catches errors from a route and sends a JSON error response.
javascript
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Something went wrong!'); }); // Error handling middleware app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
- Not using four parameters in the middleware function means Express won't treat it as error handling middleware.
- Placing error middleware before routes will not catch errors from those routes.
- Forgetting to call
next(err)or throwing errors inside async functions without proper handling can cause unhandled errors.
javascript
/* Wrong: Missing 'err' parameter, so not recognized as error middleware */ app.use((req, res, next) => { res.status(500).send('Error'); }); /* Right: Includes 'err' as first parameter */ app.use((err, req, res, next) => { res.status(500).send('Error: ' + err.message); });
Quick Reference
Error Handling Middleware Tips:
- Define with four parameters:
err, req, res, next. - Place after all routes and other middleware.
- Use
res.status()to set HTTP status code. - Send error info safely, avoid exposing sensitive details.
- Use
next(err)to forward errors to this middleware.
Key Takeaways
Error handling middleware must have four parameters: err, req, res, next.
Place error middleware after all routes to catch errors properly.
Use res.status() and res.send() or res.json() to respond with error details.
Always call next(err) or throw errors inside routes to trigger error middleware.
Avoid exposing sensitive error information in responses.