Sub topic 5
Carrying Extra Data: Codes, Statuses, and Context
This chapter assumes you can already write a class that extends Error, pass message and options to super, and set this.name. It also assumes you know ES2015 class syntax, try/catch, and how to run code in Node.js or a browser console.
A custom error class gives you a type to check. Code that handles errors usually needs more than a type, though. An HTTP layer needs a status code. A retry loop needs to know whether trying again makes sense. A support engineer reading logs needs the order ID that failed. This chapter covers how to attach that data as structured fields, how to name and shape those fields, and the traps that can quietly lose them.
Messages Are for People, Fields Are for Code
The message property is free text written for a human. It gets reworded, translated, and filled in with values. Code that branches on message text breaks as soon as someone edits the wording.
// Fragile: breaks if the wording changes
try {
throw new Error('Order 1234 was not found');
} catch (err) {
if (err.message.includes('not found')) {
console.log('handled as missing');
}
}A structured field holds a stable, machine-readable value that code can compare exactly. The message can then change freely.
class OrderError extends Error {
constructor(message, { code, orderId, ...options } = {}) {
super(message, options);
this.name = 'OrderError';
this.code = code;
this.orderId = orderId;
}
}
try {
throw new OrderError('Order 1234 was not found', {
code: 'ORDER_NOT_FOUND',
orderId: 1234,
});
} catch (err) {
if (err instanceof OrderError && err.code === 'ORDER_NOT_FOUND') {
console.log(`Missing order: ${err.orderId}`); // Missing order: 1234
}
}The constructor takes extra fields out of the options object and passes the rest to super. If the caller passes cause, it lands in options and reaches the Error constructor untouched. A later chapter covers cause in detail. For now, the point is that your constructor should not drop it.
Common Fields and What They Mean
Most projects settle on a small set of fields. Pick names once and use them across the codebase so that handlers and loggers can rely on them.
| Field | Typical type | Purpose | Example |
|---|---|---|---|
| `code` | string | Stable identifier for the kind of failure | `'EMAIL_TAKEN'` |
| `status` | number | HTTP status to send to the client | `409` |
| `retryable` | boolean | Whether trying again may succeed | `true` |
| `details` or context fields | plain object or primitives | Values that explain this specific failure | `{ field: 'email' }` |
Node.js follows the same convention. Errors from the file system carry code, errno, syscall, and path. You have probably checked code already:
// Save as read-missing.mjs and run with: node read-missing.mjs
import { readFile } from 'node:fs/promises';
try {
await readFile('missing.json', 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
console.log(`No file at ${err.path} (syscall: ${err.syscall})`);
} else {
throw err;
}
}Node's own errors use codes like ERR_INVALID_ARG_TYPE. Uppercase strings with underscores are easy to search for in logs and in source code, which is a good reason to copy the style.
A Reusable Base Class with Defaults
Repeating the same constructor in every class gets tedious and the copies drift apart. A common pattern puts the shared fields on one base class and gives them defaults.
class AppError extends Error {
constructor(
message,
{ code = 'APP_ERROR', status = 500, retryable = false, details = {}, ...options } = {}
) {
super(message, options);
this.name = 'AppError';
this.code = code;
this.status = status;
this.retryable = retryable;
this.details = details;
}
}
const err = new AppError('Email is already registered', {
code: 'EMAIL_TAKEN',
status: 409,
details: { field: 'email' },
});
console.log(err.code); // 'EMAIL_TAKEN'
console.log(err.status); // 409
console.log(err.retryable); // false
console.log(err.details.field); // 'email'
console.log(Object.keys(err)); // [ 'name', 'code', 'status', 'retryable', 'details' ]The defaults mean that every AppError has a status, so an HTTP handler never has to check for undefined. The = {} at the end of the parameter list lets callers write new AppError('Something broke') with no options at all.
The last line shows something you will need later. Fields assigned with this.x = ... are own enumerable properties. That includes name when you set it in the constructor. The built-in message and stack are not enumerable. As a result, spreading an error or passing it to JSON.stringify copies your custom fields but loses the message and stack. The serialization chapter deals with this.
Build the Message from the Fields
When a subclass knows what went wrong, let it take the raw values and write the message itself. Callers then pass data and cannot pass inconsistent text.
class InsufficientFundsError extends Error {
constructor({ accountId, balance, requested }, options) {
super(
`Account ${accountId} has ${balance}, cannot withdraw ${requested}`,
options
);
this.name = 'InsufficientFundsError';
this.code = 'INSUFFICIENT_FUNDS';
this.accountId = accountId;
this.balance = balance;
this.requested = requested;
}
}
const e = new InsufficientFundsError({ accountId: 'A-7', balance: 20, requested: 50 });
console.log(e.message); // 'Account A-7 has 20, cannot withdraw 50'
console.log(e.requested - e.balance); // 30The message reads well in a log. The fields let code compute the shortfall without parsing a string.
Gotcha: Subclass Field Declarations Erase Base Values
Class field declarations run in the subclass right after super() returns. A declaration with no initializer defines the property as undefined, and that overwrites anything the base constructor assigned.
class BaseError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
class BrokenError extends BaseError {
code; // looks harmless, resets code to undefined
constructor(message) {
super(message, 'BROKEN');
}
}
console.log(new BrokenError('x').code); // undefinedThis bites TypeScript users most often. They add code: string; to describe the property, and some compiler settings (useDefineForClassFields, which is on by default for ES2022 targets) turn that annotation into a real field. In plain JavaScript, leave out the declaration. In TypeScript, use declare code: string;, which only adds the type and emits no code.
Keep Codes in One Place
Typing string codes by hand invites typos like 'EMAIL_TAKN' that never match. Collect them in a frozen object, or as static properties on the class, and compare against those.
const ErrorCodes = Object.freeze({
EMAIL_TAKEN: 'EMAIL_TAKEN',
RATE_LIMITED: 'RATE_LIMITED',
});
class SignupError extends Error {
static codes = ErrorCodes;
constructor(message, { code, ...options } = {}) {
super(message, options);
this.name = 'SignupError';
this.code = code;
}
}
const err = new SignupError('Too many attempts', { code: SignupError.codes.RATE_LIMITED });
console.log(err.code === ErrorCodes.RATE_LIMITED); // trueA misspelled property name such as ErrorCodes.EMAIL_TAKN still gives undefined with no warning in plain JavaScript. It does fail a TypeScript check and most linters, and you only have one place to look.
What Not to Put on an Error
Errors travel far. They end up in log aggregators and crash reporters, and sometimes in API responses. Choose fields with that in mind.
- Secrets and personal data. Leave out passwords, tokens, full card numbers, and raw request bodies. Store an ID that someone can look up instead.
- Large or live objects. Request objects, sockets, and database connections are big and often circular.
JSON.stringifythrowsTypeError: Converting circular structure to JSONwhen it reaches them, and your logger may fail at the worst moment. Copy out the few primitive values you need. - Values that change. If you store a reference to a mutable object, the log shows its state when it was logged, not when it failed. Copy or freeze what matters.
- Internal detail on public responses. A
statusand acodeare safe to send to clients. Stack traces,detailsholding internal hostnames, and SQL text are not. Decide which fields are public and send only those.
Exercises
Exercise
A teammate writes class TimeoutError extends AppError { status; constructor(ms) { super(Timed out after ${ms}ms, { status: 504, retryable: true }); this.name = 'TimeoutError'; } }. Calling new TimeoutError(3000).status returns undefined. Why, and how do you fix it?
Show answer
The status; field declaration runs right after super() returns and defines status as undefined, which overwrites the 504 that the AppError constructor assigned. Remove the status; declaration (or use declare status: number; in TypeScript) so the base class value survives.
Exercise
Write a RateLimitError that extends Error, takes a retryAfter value in seconds plus an optional options object, sets name, code 'RATE_LIMITED', status 429, and retryAfter, and still supports cause.
Show answer
class RateLimitError extends Error { constructor(retryAfter, options) { super(Rate limited, retry after ${retryAfter}s, options); this.name = 'RateLimitError'; this.code = 'RATE_LIMITED'; this.status = 429; this.retryAfter = retryAfter; } } Passing options straight to super keeps cause support. Building the message from retryAfter keeps the text and the field consistent.
Exercise
A logging middleware attaches the whole req object to errors as err.request so that it is available for debugging. Name two problems this causes.
Show answer
First, req is large and contains circular references (for example through its socket), so JSON.stringify on the error throws a TypeError and structured logging fails. Second, it can leak sensitive data such as authorization headers, cookies, or request bodies into logs. Store a few primitive values instead, such as the method, path, and a request ID.