skip to content

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%

answer

  1. status read from the error
  2. only 4xx or 5xx counts
  3. the env setting decides the body
  4. HTML even for APIs

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

solid answer

~40 s

When an error reaches the end of the stack unhandled, Express's built-in handler takes `err.status`, then `err.statusCode`, if either is a number from 400 to 599; otherwise it keeps `res.statusCode` when that is already 4xx or 5xx, and falls back to 500. Headers in `err.headers` are copied only when the status came from the error. The body is a small HTML document: the escaped `err.stack` normally, but just the status message, such as 'Service Unavailable', when the app's `env` setting is `'production'`. That setting is read from `NODE_ENV` when the app is created and defaults to `'development'`, so `NODE_ENV=prod` still sends stack traces. It also logs the error to stderr unless `env` is `'test'`, and sets `Content-Security-Policy: default-src 'none'` and `X-Content-Type-Options: nosniff`. With no error and no response it sends 404 'Cannot GET /path'.

code

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

app.get('/orders/:id', (req, res) => {
  const err = new Error('Order service is restarting');
  err.status = 503;
  err.headers = { 'Retry-After': '5' };
  throw err;
});

// No custom error handler: Express's built-in handler answers.
app.listen(3000);

go deeper

for a junior

Recall that Express answers unhandled errors itself, with an HTML page that shows the stack trace outside production and a 404 'Cannot GET' page for unmatched routes.

for a middle

Explain the status order (err.status, err.statusCode, an existing 4xx/5xx res.statusCode, then 500), when err.headers apply, and how the env setting changes the body.

for a senior

Catch the leak: an environment whose NODE_ENV is not exactly production sends stack traces to clients; verify app.get('env') at startup and front the default with your own handler.

for a principal

Decide what a team's own final handler must keep from the default, such as honouring err.status and delegating once headers are sent, before it replaces the HTML body.

## When the default handler runs Express ships a **built-in final handler**. It is not a layer you register; it runs when dispatch falls off the end of the stack. Two situations lead there: - **an unhandled error**: something threw, rejected, or called `next(err)`, and no four-parameter error handler responded; - **no match**: no route or middleware sent a response, which produces a 404. Because it runs last, any custom error handler you register gets the error first, and the built-in one only sees what yours delegate with `next(err)` or never catch. Two less obvious routes lead there as well: - a custom error handler that itself throws, whose new error travels on and reaches the built-in handler when nothing after it catches it; - code that calls `next(err)` a second time for the same request; the Express guide warns that the default handler can then run even though a custom error handler is in place. ## Choosing the status For an error, the status is picked in this order: 1. `err.status`, if it is a **number from 400 to 599**; 2. otherwise `err.statusCode`, under the same rule; 3. otherwise the response's current `res.statusCode`, if a handler had already set it to a 4xx or 5xx value; 4. otherwise **500**. A status outside the error range on the error object is ignored, not copied: an error carrying `status = 302` produces a 500 (or the 4xx/5xx already on `res.statusCode`), never a redirect. Errors created by Express's own middleware already carry a suitable status. The body parsers behind `express.json()` raise errors with `status` 400 for an unparsable body and 413 for one over the size limit, which is why a malformed JSON body yields a 400 page even when you wrote no error handler. ## Headers and body The handler then builds the response: - **headers from the error**: an `err.headers` object is copied onto the response, but only when the status came from `err.status` or `err.statusCode`; - **content headers removed**: `Content-Encoding`, `Content-Language` and `Content-Range` left by earlier code are cleared; - **security headers**: `Content-Security-Policy: default-src 'none'` and `X-Content-Type-Options: nosniff`; - **content type**: always `text/html; charset=utf-8`, whatever the client asked for. The body is a minimal HTML document wrapping one message in a `<pre>` element: | `env` setting | Message in the body | |---|---| | `'production'` | the status message only, such as `Service Unavailable` | | anything else | `err.stack`, escaped, falling back to `err.toString()` | For the no-match case the message is `Cannot GET /path` (with the request's method and path), and the status is 404. Separately from the response, the handler **logs the error** to stderr with `console.error` unless `env` is `'test'`. It logs in production too; only the body changes. ## The env setting and NODE_ENV The switch is the app setting `env`, not a constructor option. Express sets it when the app is created from `process.env.NODE_ENV`, defaulting to `'development'`, and you can override it with `app.set('env', ...)`. The comparison is **exact**: only `'production'` hides stack traces. A deployment that sets `NODE_ENV=prod`, `staging` or nothing at all sends full stack traces, with file paths, to every client that triggers an error. Checking `app.get('env')` at startup is a cheap guard. A practical deployment checklist: 1. Set `NODE_ENV=production` exactly, in the process environment Express actually starts with. 2. Log `app.get('env')` once at boot, so a wrong value is visible in the first log line. 3. Request a route that fails on purpose in a pre-production environment and confirm the body carries no stack trace. The same setting also enables the `view cache` setting in production, which is a second reason to get the value exactly right. ## When the handler cannot respond If the response has already started (`res.headersSent` is true), the built-in handler cannot change the status or send its page. It logs the error and **destroys the socket**, so the client sees a truncated response on a dropped connection rather than one that looks complete. ## Why APIs usually put their own handler in front The built-in handler is a safe last resort, but it answers a JSON API with HTML and leaks stacks wherever `env` is not exactly `'production'`. Most services therefore register their own final four-parameter handler that reads the same `err.status` convention, picks the body format their API defines, and still delegates with `next(err)` once headers are sent. What that body should contain belongs to the API's error contract, not to Express.

  • Why does a malformed JSON body produce a 400 from Express's default handler even though no handler sets one?
    The parser behind `express.json()` raises its error with `status` 400 and a `type` of 'entity.parse.failed'. The default handler honours any `err.status` between 400 and 599, so it answers 400. An oversized body works the same way with status 413.
  • Does the default error handler stop logging errors in production?
    No. It logs the error to stderr with `console.error` whenever the `env` setting is anything other than 'test'. Production only changes the response body from the stack trace to the bare status message.

  • Express's default handler always answers an unhandled error with 500.
  • Any NODE_ENV value other than development hides stack traces.
  • The default handler answers JSON to clients that send Accept: application/json.
  • An err.status of 302 makes the default handler redirect the client.
  • The default handler stops logging errors when NODE_ENV is production.