How to Handle Errors in Express: Simple Guide with Examples
err, req, res, next. Place this middleware after all routes to catch and respond to errors gracefully.Why This Happens
When an error occurs in an Express route but there is no error-handling middleware, the server may crash or send incomplete responses. This happens because Express does not know how to handle the error properly without a dedicated handler.
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Something went wrong!'); }); app.listen(3000, () => console.log('Server running on port 3000'));
The Fix
Add an error-handling middleware function with four parameters: err, req, res, next. This middleware catches errors thrown in routes and sends a proper response without crashing the server.
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) => { console.error(err.message); res.status(500).send('Internal Server Error: ' + err.message); }); app.listen(3000, () => console.log('Server running on port 3000'));
Prevention
Always include an error-handling middleware at the end of your middleware stack to catch errors. Use try/catch blocks or async/await with next(err) to forward errors. Use logging to track errors and avoid exposing sensitive info to users.
Linting tools like ESLint can help enforce error handling patterns.
Related Errors
Common related errors include unhandled promise rejections and missing next(err) calls in async routes. To fix, always call next(err) inside catch blocks or use middleware like express-async-errors to handle async errors automatically.