How to Create Error Handling Middleware in Node.js
In Node.js with 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 requires four parameters: err for the error object, req for the request, res for the response, and next to pass control. It must be added after all other middleware and routes.
javascript
function errorHandler(err, req, res, next) { res.status(500).json({ message: err.message }); }
Example
This example shows a simple Express app with a route that triggers an error, and an error handling middleware that catches it and sends a JSON response with the error message.
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 will prevent Express from recognizing it as error handling middleware.
- Placing error middleware before routes means errors won't be caught.
- For async route handlers, errors must be passed to
next(err)or caught with try/catch.
javascript
import express from 'express'; const app = express(); // Wrong: Missing 'err' parameter, so this is not error middleware app.use((req, res, next) => { res.status(500).send('Error'); }); // Right: Proper error middleware app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
Quick Reference
Error Handling Middleware Tips:
- Use exactly four parameters:
err, req, res, next. - Place error middleware after all routes.
- Send meaningful error messages and proper HTTP status codes.
- For async errors, use
next(err)or try/catch blocks.
Key Takeaways
Error handling middleware must have four parameters: err, req, res, next.
Always place error middleware after all other routes and middleware.
Use res.status() to set HTTP status and send error details in the response.
For async routes, pass errors to next(err) to trigger error middleware.
Proper error handling improves app reliability and user experience.