skip to content

Four-Argument Error Handlers

Error middleware is told apart by its four parameters, and in Express 5 a rejected promise or async throw reaches it unwrapped. Interviewers ask what still needs next(err) and when to defer.

on this pageshow

questions

5

In Express 5, how does Express recognise an error-handling middleware function, and why must it be registered after the routes?

level: juniorimportance: must knowfreq 76%

answer

  1. count the declared parameters
  2. Function.length must be exactly four
  3. an unused next still counts
  4. the stack runs in registration order

basics

~20 s

Express treats a middleware function as an error handler only when it declares exactly four parameters, (err, req, res, next). Errors travel forward through the stack, so it must be registered after the routes and middleware whose errors it should catch.

solid answer

~50 s

Express's router reads each function's `length`. While an error is pending it calls only functions whose `length` is exactly 4; in a normal request it skips any function with more than three. So `(err, req, res, next)` is an error handler even when `next` is never used. Drop `next`, give it a default value, or use rest parameters, and `length` falls below 4: the function becomes ordinary middleware, skipped for errors and called for normal requests with the request object in `err`. The stack is walked in registration order and an error only moves forward, so a handler registered before the routes never sees their errors; register it last with `app.use()`. Inside it, send a response or call `next(err)`, or the request hangs. Express's built-in handler answers whatever is still unhandled when the stack runs out.

code

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

app.post('/checkout', (req, res) => {
  throw new Error('cart not found');
});

// Four parameters, registered after the routes: Express calls it for errors.
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ message: 'Checkout failed' });
});

app.listen(3000);

go deeper

for a junior

Recall the (err, req, res, next) signature, that all four parameters must be declared, and that error handlers are registered with app.use after the routes.

for a middle

Explain that the router compares Function.length to 4, which edits lower it, and why an error only reaches handlers registered after the layer that raised it.

for a senior

Diagnose the silent symptom: the built-in HTML error page appears where a custom JSON error was expected, traced to a three-parameter or defaulted handler or one mounted too early.

for a principal

Treat the arity rule as a convention to enforce: a shared error handler module, a lint rule allowing the unused next, and a test that asserts the custom error response.

## How Express tells an error handler apart Express has no separate registration call for error handling. You pass an error handler to the same `app.use()` (or `router.use()`, or a route method) as any other middleware, and Express decides what it is by **arity**: the number of parameters the function declares, which JavaScript exposes as `Function.length`. The decision lives in the router that Express 5 bundles. Each registered function is wrapped in a *layer*, and the layer has two entry points: - **Normal dispatch** calls the function as `(req, res, next)` only if its `length` is 3 or less. A function with four or more parameters is skipped. - **Error dispatch**, used while an error is pending, calls the function as `(err, req, res, next)` only if its `length` is **exactly 4**. Anything else is skipped and the error moves on. Parameter **names** play no part. `(e, rq, rs, nx)` is an error handler; `(err, req, res)` is not, however it is named. ## Mistakes that change the count `Function.length` counts the parameters declared *before* the first one with a default value, and never counts a rest parameter. Several innocent-looking edits therefore turn an error handler into ordinary middleware: | Declaration | `length` | What Express treats it as | |---|---|---| | `(err, req, res, next) => {}` | 4 | error handler | | `(err, req, res) => {}` | 3 | ordinary middleware | | `(err, req, res, next = () => {}) => {}` | 3 | ordinary middleware | | `(...args) => {}` | 0 | ordinary middleware | | `function (err, req, res, next) {}` | 4 | error handler | The demoted function causes two problems. While an error is pending it is skipped, so the error falls through to Express's built-in handler and the custom response never appears. And in a normal request that reaches it (an unmatched URL, say) it *is* called, with `req` arriving in the `err` parameter and `next` arriving in `res`. A body such as `res.status(500)` then throws `TypeError: res.status is not a function`, which Express forwards as a fresh error. Linters often flag the unused `next`. Keep it and silence the rule (or name it `_next`); deleting it is a behaviour change, not a style fix. TypeScript annotations do not help either: types are erased, and Express inspects the compiled function. ## Where the error handler goes in the stack The router walks the stack **in the order things were registered**, and an error only ever moves forward from the layer that raised it. In outline, for one request: 1. Ordinary middleware and matching routes run in order. 2. When a handler throws, rejects, or calls `next(err)`, the router enters error mode and keeps walking **forward**, skipping every ordinary function and every route. 3. The first four-parameter function it meets is called with the error. 4. If nothing handles it before the stack ends, Express's built-in handler responds. So an error handler registered *before* the routes is simply behind the error; it never runs for their failures. The guide's rule follows from that: define error-handling middleware **last**, after the other `app.use()` calls and the routes. The same holds inside an `express.Router`. A four-parameter function registered on a router catches errors raised earlier in that router's stack; if it is absent, or calls `next(err)`, the error leaves the router and continues through the parent app's later layers. ## What an error handler must do An error handler is still middleware, so it ends in one of two ways: - **respond**: set a status and send a body, which finishes the request; - **delegate**: call `next(err)` to hand the error to the next error handler or, at the end, to Express's built-in one. If it does neither, the request hangs until the client gives up. You may register several error handlers (one that logs and delegates, one that answers certain requests, a final catch-all); each must respond or delegate. ## Why this is an interview staple The arity rule is the one place where Express's behaviour depends on a function's declared shape rather than on what it does, and the failure is silent: no warning at registration, just the built-in HTML page where a JSON body was expected. A candidate who knows it can diagnose that symptom at once and explains why the unused `next` must stay.

  • What happens when a request with no error reaches a three-parameter function that was meant to handle errors?
    Express calls it as ordinary middleware, so `req` lands in `err`, `res` in `req` and `next` in `res`. Code like `res.status(500)` then throws `TypeError: res.status is not a function`, Express forwards that as a new error, and the built-in handler answers it with a 500 page.
  • Can an express.Router have its own error handler, and what happens to errors it does not handle?
    Yes. A four-parameter function registered with `router.use()` catches errors raised earlier in that router's stack. If the router has none, or its handler calls `next(err)`, the error leaves the router and continues through the parent app's later layers until an app-level error handler or the built-in one answers it.
  • Does annotating the parameters in TypeScript keep a handler without next recognised as an error handler?
    No. Types are erased at compile time and Express inspects the compiled function's `length`. A handler declared with three parameters is ordinary middleware whatever its annotations say, so keep `next` declared and silence the unused-parameter lint rule instead.

  • Express recognises error handlers by the parameter named err.
  • An unused next can be deleted from an error handler with no effect.
  • Express moves four-argument middleware to the end of the stack automatically.
  • A default value on next keeps the function an error handler.
  • An error handler that logs the error and returns has finished the request.
open as a page

In an Express 5 checkout route, which failures reach error middleware by themselves, and which still need an explicit next(err)?

level: middleimportance: must knowfreq 80%

basics

~20 s

In Express 5, synchronous throws, async-function throws and rejections of a returned promise reach error middleware automatically. Callback errors, un-returned promise chains and timer callbacks do not: pass them to next(err), or the request hangs or the process crashes.

open as a page

In Express 5, how does the built-in default error handler choose the status, headers and body for an error nothing else handled?

level: middleimportance: should knowfreq 52%

basics

~20 s

Express's default handler uses err.status or err.statusCode when it is from 400 to 599, else a 4xx or 5xx res.statusCode, else 500. It sends an HTML page holding err.stack, or only the status message when the env setting is 'production'.

open as a page

An Express 5 CSV export fails midway through streaming and the logs show ERR_HTTP_HEADERS_SENT instead of the real cause; why, and what should the error handler do?

level: seniorimportance: should knowfreq 46%

basics

~20 s

The error handler tries res.status(500).json() after the 200 headers went out; res.json throws ERR_HTTP_HEADERS_SENT, which replaces the real error. Check res.headersSent first and return next(err): Express's default handler logs the original and destroys the socket.

open as a page

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%

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'.

open as a page