A centralized error handler helps catch and manage all errors in one place. This keeps your code clean and makes debugging easier.
0
0
Centralized error handler in Express
Introduction
When you want to handle errors from many routes in one place.
When you want to send consistent error messages to users.
When you want to log errors for debugging without repeating code.
When you want to avoid crashing the server on unexpected errors.
Syntax
Express
app.use((err, req, res, next) => {
// handle error here
res.status(500).send('Something broke!');
});This middleware has four parameters: err, req, res, and next. Express knows this is an error handler because it has four arguments.
Place this middleware after all other routes and middleware.
Examples
Logs the error stack to the console and sends a 500 status with a message.
Express
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});Sends different responses based on error type.
Express
app.use((err, req, res, next) => {
if (err.type === 'database') {
res.status(503).send('Database error');
} else {
res.status(500).send('Server error');
}
});Sample Program
This Express app throws an error on the home route. The centralized error handler catches it, logs the message, and sends a friendly error response.
Express
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Oops!'); }); // Centralized error handler app.use((err, req, res, next) => { console.error('Error caught:', err.message); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always place the error handler after all other middleware and routes.
Use next(err) in your routes to pass errors to this handler.
Customize error responses for better user experience.
Summary
Centralized error handlers catch all errors in one place.
They keep your code clean and consistent.
Place them last in your middleware stack.