Skip to content

Error cause: chain errors without losing them (ES2022)

  • How new Error(message, { cause }) attaches the original error to a new one.
  • Exactly when the cause property is created, and why JSON.stringify does not show it.
  • How to forward cause through custom error classes.
  • How to log and serialize a chain of causes safely.

TL;DR: every built-in error constructor accepts an options object as its last argument. If that object has a cause property, the new error gets an own cause property with the same value. Use it when you catch a low-level error and throw a higher-level one, so the message describes what failed at your layer while cause keeps why.

It was added in ECMAScript 2022 and is supported by every current browser and server runtime (details in Compatibility).

Layers of an application translate errors. A data-access layer catches a SyntaxError from JSON.parse or a network failure from fetch and throws “Could not load order o-1”, which is what the caller needs to know. Before ES2022 the common patterns all lost something: re-throwing the original error lost the context, copying err.message into the new message lost the original type and stack, and custom properties such as originalError were non-standard, so loggers and debuggers ignored them.

Running the samples: save each sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23.

The OrdersPortal app parses an order from a truncated response:

function parseOrder(json) {
return JSON.parse(json);
}
// Before: the original error survives only as text in the message.
try {
try {
parseOrder('{"id": "o-1",');
} catch (err) {
throw new Error(`Could not load order o-1: ${err.message}`);
}
} catch (error) {
console.log(error.message);
console.log('original error object:', error.cause); // undefined: it is gone
}
// After: keep a clear message for this layer and the original error as `cause`.
try {
try {
parseOrder('{"id": "o-1",');
} catch (err) {
throw new Error('Could not load order o-1', { cause: err });
}
} catch (error) {
console.log(error.message);
console.log(error.cause instanceof SyntaxError, error.cause.name);
}

Output:

Could not load order o-1: Expected double-quoted property name in JSON at position 13 (line 1 column 14)
original error object: undefined
Could not load order o-1
true SyntaxError

With cause, the caller can still check the original error’s type, read its stack, and decide whether to retry, while the message stays readable.

// Fragment: signatures
new Error(message, { cause });
new TypeError(message, { cause }); // also RangeError, SyntaxError, ReferenceError, EvalError, URIError
new AggregateError(errors, message, { cause });

The specification’s InstallErrorCause step runs inside each constructor: if the options argument is an object and has a cause property, define an own, non-enumerable cause property with that value. Every observable rule follows from that sentence:

const e1 = new Error('outer', { cause: 'plain string' });
console.log(e1.cause); // any value is allowed
console.log(Object.getOwnPropertyDescriptor(e1, 'cause'));
console.log(Object.keys(e1), JSON.stringify(e1)); // non-enumerable
const e2 = new Error('no options');
console.log('cause' in e2); // false: no property at all
const e3 = new Error('explicit undefined', { cause: undefined });
console.log('cause' in e3, e3.cause); // true undefined
const e4 = new Error('not an object', 'oops');
console.log('cause' in e4); // false: options ignored
const e5 = new TypeError('bad id', { cause: { orderId: 'o-1' } });
console.log(e5.cause);
const e6 = new AggregateError([new Error('a')], 'all failed', { cause: 'upstream' });
console.log(e6.cause);

Output:

plain string
{
value: 'plain string',
writable: true,
enumerable: false,
configurable: true
}
[] {}
false
true undefined
false
{ orderId: 'o-1' }
upstream

Points worth remembering:

  • Any value can be a cause: an error, a string, an object with context. An Error is the most useful because it carries a stack.
  • Presence is checked with HasProperty, so { cause: undefined } still creates the property. 'cause' in error tells you whether a cause was given at all.
  • There is no Error.prototype.cause. Errors created without the option have no cause property.
  • Non-enumerable, like message, so Object.keys, spread and JSON.stringify skip it.
  • Tooling understands it. Node.js util.inspect (and therefore console.log) prints nested [cause] entries with their stacks. MDN’s compatibility data notes that Chrome’s console prints the cause from version 125, while Safari’s console does not print it.
const root = new Error('connect ECONNREFUSED db.example.test:5432');
const mid = new Error('Order repository query failed', { cause: root });
const top = new Error('Could not load order o-1', { cause: mid });
console.log(top);

Output (stack frames shortened):

Error: Could not load order o-1
at file:///.../cause-chain.mjs:3:13 ... {
[cause]: Error: Order repository query failed
at file:///.../cause-chain.mjs:2:13 ... {
[cause]: Error: connect ECONNREFUSED db.example.test:5432
at file:///.../cause-chain.mjs:1:14 ...
}
}

Platform APIs use the same convention: Node.js’s built-in fetch rejects with TypeError: fetch failed and puts the underlying network error in cause, so error.cause is where the useful detail is.

OrderApiClient in OrdersPortal wraps three kinds of failure in one OrderApiError class, forwarding cause to Error, and a small serializer writes the whole chain into structured logs:

// order-api-client.mjs - wrap low-level failures without losing them.
export class OrderApiError extends Error {
constructor(message, { status, orderId, ...options } = {}) {
super(message, options); // forwards { cause } to Error
this.name = 'OrderApiError';
this.status = status;
this.orderId = orderId;
}
}
export async function getOrder(orderId) {
let response;
try {
response = await fetch(`https://api.example.test/orders/${orderId}`);
} catch (err) {
throw new OrderApiError(`Network error while loading order ${orderId}`, { orderId, cause: err });
}
if (!response.ok) {
throw new OrderApiError(`Order ${orderId} returned HTTP ${response.status}`, { orderId, status: response.status });
}
try {
return await response.json();
} catch (err) {
throw new OrderApiError(`Order ${orderId} sent invalid JSON`, { orderId, status: response.status, cause: err });
}
}
// Walk the chain for logs. `cause` is non-enumerable, so JSON.stringify skips it.
export function serializeError(error, depth = 0) {
if (!(error instanceof Error)) return { value: String(error) };
const out = { name: error.name, message: error.message };
for (const key of ['status', 'orderId']) if (error[key] !== undefined) out[key] = error[key];
if ('cause' in error) {
out.cause = depth < 5 ? serializeError(error.cause, depth + 1) : { value: '[cause chain truncated]' };
}
return out;
}
// --- Demo with a mocked fetch.
globalThis.fetch = async (url) => {
if (url.endsWith('/o-1')) return { ok: true, status: 200, json: async () => JSON.parse('{"id": "o-1",') };
if (url.endsWith('/o-2')) throw new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND api.example.test') });
return { ok: false, status: 404 };
};
for (const id of ['o-1', 'o-2', 'o-3']) {
try {
await getOrder(id);
} catch (error) {
console.log(JSON.stringify(serializeError(error)));
}
}

Output:

{"name":"OrderApiError","message":"Order o-1 sent invalid JSON","status":200,"orderId":"o-1","cause":{"name":"SyntaxError","message":"Expected double-quoted property name in JSON at position 13 (line 1 column 14)"}}
{"name":"OrderApiError","message":"Network error while loading order o-2","orderId":"o-2","cause":{"name":"TypeError","message":"fetch failed","cause":{"name":"Error","message":"getaddrinfo ENOTFOUND api.example.test"}}}
{"name":"OrderApiError","message":"Order o-3 returned HTTP 404","status":404,"orderId":"o-3"}

Each layer adds context: the client says which order failed, fetch says the request failed, and the innermost error says DNS lookup failed. The HTTP 404 case has no lower-level error, so it has no cause. The depth limit protects against very long or circular chains (a.cause = b; b.cause = a is legal).

  • Custom error classes that drop the options. A constructor that calls super(message) silently discards cause:

    class ValidationError extends Error {
    constructor(message) {
    super(message);
    this.name = 'ValidationError';
    }
    }
    const e = new ValidationError('invalid order', { cause: new Error('missing id') });
    console.log('cause' in e); // false

    Accept an options parameter and pass it to super(message, options).

  • Passing the cause as the second argument. new Error('failed', err) ignores err unless it happens to be an object with a cause property. Always wrap it: { cause: err }.

  • Relying on JSON.stringify(error). It prints {} for most errors. Serialize name, message, stack and cause explicitly.

  • Copying the cause’s message into the new message. This duplicates text in logs and can leak internal details (hostnames, SQL) into user-facing messages. Keep the outer message about your layer; let cause carry the detail to logs only.

  • Wrapping at every layer. A five-deep chain where each level says “failed” is noise. Wrap where the meaning changes, such as at a module or service boundary.

  • Showing cause to end users. It may contain internal data. Log it; show a safe message.

Use cause when you translate an error: a lower layer’s failure becomes a domain error, and the original is needed for debugging or retry decisions. Do not wrap when:

  • You have nothing to add. Re-throw the original error as is.
  • Several errors caused one failure. Use AggregateError (for example the rejection from Promise.any), and give it a cause only if there is a single higher-level reason.
  • The “cause” is just data. A field such as orderId or status belongs in its own property, as in OrderApiError, where code can read it without walking the chain.

According to MDN’s browser compatibility data, the cause option and property are supported in Chrome 93, Edge 93, Firefox 91, Safari 15 (including iOS), Node.js 16.9.0, Deno 1.13 and Bun 1.0. Internet Explorer never supported them. In older runtimes the options argument is ignored, so code still runs but the cause is lost; a polyfill such as core-js can add it.

TypeScript: lib.es2022.error.d.ts adds the ErrorOptions interface (cause?: unknown), the options parameter on every error constructor, and Error.cause?: unknown. Add es2022 or later to lib if a project pins an older one. Because cause is unknown, narrow it (for example error.cause instanceof Error) before reading its properties.

1. What does { cause } do, and why not just put the original message in the new message? It stores the original value in an own, non-enumerable cause property of the new error. Unlike string concatenation, it keeps the original’s type, stack and custom properties, so code can still inspect it and tools such as Node.js console.log can print the whole chain.

2. Is new Error('x', { cause: undefined }).cause the same as new Error('x').cause? The value is undefined in both cases, but the first error has an own cause property and the second has none, because the specification checks whether the options object has a cause property. 'cause' in error distinguishes them.

3. Why might a custom error class lose its cause? Because its constructor does not forward the options argument to super. Only the built-in constructor installs cause, so subclasses must call super(message, options).

4. Senior scenario: your team’s logs show only “Request failed” for outages, and nobody can tell DNS failures from timeouts. How do you redesign error handling? Define a small set of domain error classes at service boundaries (such as OrderApiError) that accept ErrorOptions and forward cause, plus structured fields like status and orderId. Wrap only where the meaning changes, always passing the caught error as cause. Write one serializer that walks the cause chain with a depth limit and emits name, message, stack and fields per level to the structured logger, and check that the log pipeline does not rely on JSON.stringify(error). Keep user-facing messages generic and never expose the chain to clients. Finally, add a lint rule or review checklist item for catch blocks that throw a new error without cause.

  • new Error(message, { cause }) (ES2022) keeps the original error attached to the one you throw.
  • The property exists only when the options object has a cause key; it is own and non-enumerable.
  • Custom error classes must forward the options to super.
  • Serialize cause chains explicitly, with a depth limit; JSON.stringify skips them.
  • Use AggregateError for many causes and plain properties for data.