skip to content

After a logging error middleware is added to an Express 5 app, failing requests return 404 'Cannot GET' instead of 500; what went wrong?

level: seniorimportance: should knowfreq 40%

answer

  1. the argument to next decides
  2. an empty next clears the error
  3. route and router are signals
  4. dispatch resumes, nothing matches

basics

~20 s

The logging handler calls next() instead of next(err). In Express, next() with no argument clears the pending error, so dispatch resumes with ordinary middleware and routes after it; nothing matches, and Express's built-in handler answers 404 'Cannot GET /path'.

solid answer

~40 s

In Express the argument to `next` sets the mode. `next()`, or any falsy value, means carry on normally; `next('route')` and `next('router')` are routing signals; anything else is an error and switches the router into error mode, skipping ordinary middleware and routes until a four-parameter function runs. A logging error handler that ends with `next()` therefore drops the error: dispatch resumes with whatever ordinary layers follow it, none of which match an already-handled path, and the built-in handler sends 404 'Cannot GET /path'. If a catch-all ordinary middleware is registered later, it answers instead. The fix is `next(err)`. Each error handler in a chain must respond or call `next(err)`; one that throws, or returns a rejected promise, hands the next one the new error in place of the original.

code

javascript · 20 lines
javascript
const express = require('express');
const app = express();

app.get('/orders/:id', () => {
  throw new Error('order lookup failed');
});

// Logs, then passes the SAME error on. Calling next() here would clear it.
app.use((err, req, res, next) => {
  console.error(err);
  next(err);
});

// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  res.status(err.status || 500).json({ message: 'Something failed' });
});

app.listen(3000);

go deeper

for a junior

Recall that next() continues normally and next(err) reports an error, and that an error handler that logs must still pass the error on.

for a middle

Explain how the router reads next's argument, including the 'route' and 'router' signals, and how a chain of error handlers responds or delegates.

for a senior

Read the symptom: a 404 'Cannot GET' for an existing path means the error was cleared, and trace it to a next() in a logging stage or a falsy synchronous throw.

for a principal

Standardise the error chain shape for the team, with one logging stage and one final responder, and require an HTTP test of each service's error path.

## The argument to next is a switch Every Express middleware receives `next`, and the router reads its argument to decide what happens next: | Call | Meaning to the router | |---|---| | `next()` or a falsy value | no error: continue normal dispatch | | `next('route')` | skip the remaining callbacks of the current route | | `next('router')` | leave the current router and continue in its parent | | `next(anything else)` | an error: enter error mode | "Anything else" is broad. An `Error`, a string such as `'fail'`, or a plain object like `{ status: 404 }` all count as errors; only the two exact strings `'route'` and `'router'` are signals. In error mode the router keeps walking the stack forward but calls only four-parameter functions, skipping every ordinary middleware and every route. ## What the logging handler did The new middleware looked like this: ```js app.use((err, req, res, next) => { console.error(err); next(); }); ``` It has four parameters, so Express calls it for errors. But `next()` carries no argument, so the router **clears the pending error** and resumes ordinary dispatch from that point: 1. a route throws; the router enters error mode and reaches the logging handler; 2. the handler logs and calls `next()`; the error is gone; 3. the router continues with ordinary layers registered after it; routes registered earlier are behind it and never revisited; 4. nothing responds, so Express's built-in handler treats the request as unmatched and answers **404 `Cannot GET /path`**. The final error handler further down is never reached, because it only runs for errors and there is no longer one. If the app had a catch-all ordinary middleware after the logger, such as a custom 404 handler, that would answer instead, which is just as wrong. The fix is one argument: `next(err)`. ## Chaining several error handlers Splitting error handling into stages is a documented Express pattern: one function logs, another answers requests of a certain kind, a last one answers everything else. Each stage must do exactly one of two things: - **respond** with a status and body, which ends the chain; - **delegate** with `next(err)`, passing the same error on. Two other outcomes cause trouble: - **neither**: the request hangs, because nothing ever answers it; - **throws, or returns a rejected promise**: the router invokes error handlers inside the same `try/catch` and rejection watching it uses for routes, so the **new** error is passed to the next error handler, and the original is lost unless it was logged first. ## A synchronous throw of a falsy value The same switch explains a rarer bug. A synchronous `throw undefined` (or `throw null`) in a route is caught by the router and passed to `next(undefined)`, which reads as **no error**, so the request carries on and usually ends in the 404. An `async` handler doing the same is safer in Express 5: a falsy rejection reason is replaced with `new Error('Rejected promise')` before it is forwarded. ## How to keep the chain honest A few habits prevent the bug: 1. End every pass-through error handler with `next(err)`, never `next()`. 2. Give the final error handler no exit except a response, and guard it with `res.headersSent` before writing one. 3. Throw only `Error` objects, so a falsy or odd value never reaches `next`. 4. Cover the error path with an HTTP test that asserts the status and body of a failing route, which catches a 404 where a 500 belongs. ## How the bug shows up The tell-tale signs are consistent enough to diagnose from a dashboard: - the status mix for a failing endpoint shifts from 5xx to 404 the day the logging stage ships; - the error is logged once by the new stage, but the final handler's own log line never appears; - the 404 body is Express's built-in `Cannot GET /path` page, not the API's usual error body. The symptom is worth recognising on sight: a 404 'Cannot GET' page for a path that clearly exists means the error was cleared somewhere between where it was raised and where it should have been answered.

  • In an Express 5 error chain, what happens when the second error handler throws while building its response?
    The router calls error handlers inside a `try/catch` and watches a returned promise, just as it does for routes. The throw becomes a new `next(err)`, so the next four-parameter handler, or the built-in one, receives the new error. The original is lost unless an earlier stage logged it.
  • Is next('route') ever treated as an error in Express?
    No. The exact strings 'route' and 'router' are routing signals: the first skips the rest of the current route's callbacks, the second leaves the current router. Any other value passed to `next`, including a different string or a plain object, puts the router into error mode.

  • Calling next() from an error handler passes the error along.
  • Only Error objects passed to next are treated as errors.
  • An error handler that throws has its error ignored by Express.
  • A logging error handler should call next() so the request can finish.
  • next('route') puts the router into error mode.

Assumes Express 5, whose router forwards a rejected promise from any handler, error handlers included; how next() and next(err) steer dispatch is unchanged from Express 4.