How to Fix Express.js Error Middleware Not Working
In this tutorial, you'll learn about How to Fix Express.js"Express" >}}.js Error Middleware Not Working. We cover key concepts, practical examples, and best practices.
The Problem
Express.js error handling middleware does not catch errors, causing the server to crash or return unhelpful HTML error pages instead of the structured JSON error response.
Quick Fix
Step 1: Use four parameters
Express identifies error middleware by its arity (four parameters):
app.use((err, req, res, next) => {
res.status(500).json({ error: 'Something broke!' });
});
If you omit any parameter, Express treats it as regular middleware:
// This is regular middleware, NOT error middleware
app.use((err, req, res) => {
res.status(500).json({ error: 'Something broke!' });
});
Step 2: Place error middleware after all routes
Error middleware must be registered last:
// WRONG: error middleware before routes
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
app.get('/users', (req, res) => {
throw new Error('DB error');
});
Correct order:
app.get('/users', (req, res, next) => {
next(new Error('DB error'));
});
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});
Step 3: Call next(error) in async handlers
Async errors must be passed to next:
app.get('/users', async (req, res) => {
const users = await db.findUsers(); // If this throws, Express does not catch it
res.json(users);
});
Wrap in try/catch:
app.get('/users', async (req, res, next) => {
try {
const users = await db.findUsers();
res.json(users);
} catch (err) {
next(err);
}
});
Or use a wrapper:
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.get('/users', asyncHandler(async (req, res) => {
const users = await db.findUsers();
res.json(users);
}));
Step 4: Do not send headers after error middleware
Check if headers are already sent:
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
res.status(500).json({ error: err.message });
});
Prevention
- Place error middleware after all routes and
app.use()calls. - Use four parameters in error middleware.
- Wrap async route handlers with error catching.
- Use Express 5 (beta) which handles async errors automatically.
- Standardize error formatting in a single error middleware.
Common Mistakes with express error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world NODE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro