skip to content

How do you test an Express 5 error path with Supertest so the assertion proves your four-argument error handler answered, not the default handler?

level: middleimportance: should knowfreq 45%

answer

  1. both handlers can send 503
  2. the default answers in HTML
  3. assert the content type and shape
  4. async throw reaches error middleware

basics

~20 s

Assert more than the status: Express 5's default error handler also takes the status from err.status, but it answers text/html with the stack outside production. Expect your JSON content type and body shape, so a test only passes when the custom handler ran.

solid answer

~40 s

In Express 5 an `async` route that throws, or returns a rejected promise, reaches error middleware without a wrapper, so the test can drive the real failure with `request(app).get('/api/reports/42')`. A status-only `.expect(503)` proves little: Express's built-in handler also sets the status from `err.status` or `err.statusCode` when it is 4xx or 5xx. What differs is the body. The default handler sends `text/html; charset=utf-8`, with `err.stack` as the text unless the app's `env` setting is `production`, while your handler sends the contracted JSON. So chain `.expect(503)`, `.expect('Content-Type', /json/)` and an assertion on the body, which fails if the custom handler is missing, registered before the routes, or declared with three parameters.

code

javascript · 16 lines
javascript
const express = require('express');

const app = express();

app.get('/api/reports/:id', async (req, res) => {
  const err = new Error(`report ${req.params.id} unavailable`);
  err.status = 503;
  throw err; // Express 5 forwards the rejection to error middleware
});

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  res.status(err.status ?? 500).json({ error: err.message });
});

module.exports = app;

go deeper

for a junior

Remember that an error test should check the status, the content type and the body, not the status alone.

for a middle

Explain why: Express 5 forwards async rejections, and the default handler also uses err.status but answers HTML with the stack outside production.

for a senior

Use error-path tests to catch handler order, arity and next(err) mistakes, and keep them independent of NODE_ENV-dependent default output.

for a principal

Decide the small fixed set of error-path tests every service carries, so the error contract is enforced the same way across a team.

## The two handlers that can answer an error An **error-handling middleware** in Express is a function with four parameters, `(err, req, res, next)`, registered with `app.use()` after the routes. When a route fails, Express skips the remaining ordinary middleware and calls the error handlers registered after that point, in order. If each of them passes the error on with `next(err)`, or none is registered, Express's **default error handler** answers at the end of the stack. Testing an error path with **Supertest** means sending a real request that makes a route fail and checking the response. The trap is that both handlers can produce the *same status*, so a test that checks only the status cannot tell them apart. ## What Express 5 does with a failing async route In Express 5, a route handler or middleware that **returns a promise** has its rejection forwarded to error middleware, as if it had called `next(err)`. An `async` function always returns a promise, so `throw` inside it, or an `await` on a rejected call, reaches the error handlers with no wrapper. The test can therefore trigger the failure exactly as production would: no stubbing of `next`, no helper around the route. Express 4 did not do this: a rejection from an `async` handler was not forwarded, so the request never reached error middleware. The rejection went unhandled and no response was sent, so a Supertest test of such a route saw a timeout or a crashed process rather than an error response. ## How the default handler answers | Aspect | Default handler | A typical custom JSON handler | |---|---|---| | Status | `err.status` or `err.statusCode` if it is 4xx or 5xx; otherwise an error status already set on the response, or 500 | whatever your handler sets | | `Content-Type` | `text/html; charset=utf-8` | `application/json; charset=utf-8` | | Body | an HTML page holding `err.stack`, or the status message when `env` is `production` | the contracted JSON error body | | Extra headers | `Content-Security-Policy: default-src 'none'`, `X-Content-Type-Options: nosniff`, plus `err.headers` when the status came from the error | whatever your handler sets | | Logging | `console.error(err)` unless the app's `env` is `test` | whatever your handler does | The app's `env` setting defaults to `process.env.NODE_ENV`, or `development` when that is unset. Two testing consequences follow: - running the suite with `NODE_ENV=test` silences the default handler's logging, which keeps output clean but also hides the fact that it ran; - the default handler's body changes between `production` and everything else, so asserting on its exact text makes a test environment-dependent. ## Assertions that prove the custom handler ran 1. **Status first**: `.expect(503)`, so a 500 from an unexpected failure is reported plainly. 2. **Content type**: `.expect('Content-Type', /json/)`. This is what fails when the default handler answered, since it always sends HTML. 3. **Body shape**: `.expect(503, { error: 'report 42 unavailable' })`, or await the response and assert on `res.body` with the test runner's assertions. 4. **Nothing leaked**: for a handler that must hide internals, assert that the body carries no stack text. A test built this way fails in each of the classic wiring mistakes: - the error handler is registered **before** the routes, so errors from those routes never reach it; - it is declared with **three** parameters, so Express treats it as ordinary middleware and skips it for errors; - it calls `next(err)` for this case instead of responding, handing the request to the default handler; - the route's failure is a callback error that is never passed to `next(err)`, so no handler runs; if the route also never responds, the request hangs and the runner reports a timeout. ## Choosing what to fail on Keep a small set of error-path tests per app rather than per route: one route that throws synchronously, one `async` route that rejects, one unknown path reaching the 404 handler, and one error carrying a 4xx `err.status`. Each asserts status, content type and body. Together they pin down the error contract, and any change to handler order or arity shows up as a failure with a clear message, such as `expected "Content-Type" matching /json/, got "text/html; charset=utf-8"`. Driving these failures through real routes, rather than calling the error handler as a function with fake objects, is what proves the registration: the order of `app.use()` calls and the handler's arity only matter when Express itself dispatches the request.

  • Why does running the suite with NODE_ENV=test change what you see when Express's default error handler runs?
    The app's `env` setting comes from `NODE_ENV`, and the default handler skips its `console.error` log when `env` is `test`. The response still carries the stack, because only `production` hides it, but the log line that would reveal the default handler ran disappears.
  • An Express 5 error handler is written as (err, req, res) => { ... }. What does a Supertest error-path test show?
    Express recognises error middleware by its four parameters, so a three-parameter function is skipped for errors. The default handler answers instead, with the right status if `err.status` is set but an HTML body, so a test asserting the JSON content type or body fails.

  • Asserting the status code alone proves the custom error handler ran.
  • An async route in Express 5 needs a wrapper before its error reaches the handler.
  • Express's default error handler always answers 500.
  • The default handler answers JSON when the request accepts JSON.
  • Asserting on the default handler's stack text gives a stable test.

Assumes Express 5, which forwards a rejected promise from a route or middleware to error middleware; Express 4 needed next(err) or a wrapper for async handlers.