Skip to content

How to Fix Express.js Error Middleware Not Working

DodaTech Updated 2026-06-24 3 min read

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

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

### Why does Express not catch errors from async functions?

Express 4 does not handle promise rejections from async route handlers. If an async function throws, the promise rejects, but Express does not have a .catch() on the returned promise. Express 5 will handle this automatically. In Express 4, you must use try/catch and next(err) or a wrapper.

Can I have multiple error middleware?

Yes. Multiple error middleware functions run in sequence if they call next(). This is useful for logging, formatting, and then sending the response. Each error middleware should either send a response or call next(err) to pass to the next error handler.

How do I distinguish between different error types?

Check the error properties or use custom error classes:

class NotFoundError extends Error {
    constructor(message) { super(message); this.status = 404; }
}
app.use((err, req, res, next) => {
    const status = err.status || 500;
    res.status(status).json({ error: err.message });
});

Define custom errors with status codes and handle them in a single error middleware.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro