Sub topic 8
Attaching the Original Error with cause
This chapter assumes you can write a custom error class with class ... extends Error, set its name, and catch errors with try/catch and instanceof. It covers the cause option that ES2022 added to the Error constructor. You will see how to pass it, how custom classes must forward it, and how runtimes display it. Later chapters cover wrapping strategy at layer boundaries, walking long chains, and the exact property definition.
The problem cause solves
Code often catches a low-level error and throws a more meaningful one. A JSON parser fails, and your code reports "Failed to load config." The new error describes the operation that failed. The original error holds the detail you need for debugging: the exact syntax problem, its type, and its stack trace.
Before ES2022 there were two common workarounds, and both lost information.
| Approach | What you keep | What you lose |
|---|---|---|
| Concatenate messages: `new Error('Load failed: ' + err.message)` | The low-level text | The original type, stack, and custom fields such as `code` |
| Custom field: `e.originalError = err` | The full original object | Standard tooling support; every library picks a different field name |
| `new Error('Load failed', { cause: err })` | The full original object, in a standard place | Nothing |
Because cause is part of the language, Node.js, browser devtools, logging libraries, and test runners all know where to look for it.
The syntax
The Error constructor takes an optional second argument, an options object. If that object has a cause key, the new error gets a cause property set to that value.
function parsePort(text) {
const n = Number(text);
if (!Number.isInteger(n)) throw new TypeError(`Not an integer: ${text}`);
if (n < 1 || n > 65535) throw new RangeError(`Port out of range: ${n}`);
return n;
}
function readPortSetting(env) {
try {
return parsePort(env.PORT);
} catch (err) {
throw new Error('Invalid PORT setting', { cause: err });
}
}
try {
readPortSetting({ PORT: '99999' });
} catch (err) {
console.log(err.message); // 'Invalid PORT setting'
console.log(err.cause instanceof RangeError); // true
console.log(err.cause.message); // 'Port out of range: 99999'
}The outer error names the operation ("reading the PORT setting"). The inner error says what went wrong ("out of range"). A caller can check either one.
Inside a catch block, the shorthand { cause } reads well when you name the binding cause:
try {
JSON.parse('{ not json');
} catch (cause) {
const err = new Error('Could not parse settings', { cause });
console.log(err.cause instanceof SyntaxError); // true
}Every built-in error type accepts it
The options argument is not limited to Error. TypeError, RangeError, SyntaxError, ReferenceError, EvalError, and URIError all accept (message, options). AggregateError takes the options as its third argument because its first argument is the list of errors:
const low = new Error('socket closed');
const t = new TypeError('Bad response shape', { cause: low });
const a = new AggregateError([low], 'All mirrors failed', { cause: low });
console.log(t.cause === low); // true
console.log(a.cause === low); // trueCustom classes must forward options
This is the most common mistake. A custom class gets cause support only if it passes the options object to super. If the constructor accepts only message, the second argument is silently dropped.
class BrokenError extends Error {
constructor(message) {
super(message); // options never reach Error
this.name = 'BrokenError';
}
}
class WorkingError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'WorkingError';
}
}
const original = new Error('disk full');
console.log(new BrokenError('Save failed', { cause: original }).cause); // undefined
console.log(new WorkingError('Save failed', { cause: original }).cause === original); // trueNo error or warning tells you that BrokenError dropped the cause. Make options the last constructor parameter of every custom error class, including subclasses whose constructors take extra arguments first:
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
const err = new HttpError(502, 'Bad gateway', { cause: new Error('ECONNREFUSED') });
console.log(err.status); // 502
console.log(err.cause.message); // 'ECONNREFUSED'Passing the cause the wrong way
The second argument must be an object with a cause key. Passing the error directly looks reasonable but does not do what you expect:
const inner = new Error('timeout');
const wrong = new Error('Request failed', inner);
console.log(wrong.cause); // undefined
const right = new Error('Request failed', { cause: inner });
console.log(right.cause === inner); // trueThe constructor treats inner as the options object and looks for a cause property on it. inner has none, so the result has no cause. It gets worse when inner has a cause of its own. Then wrong.cause silently becomes inner.cause, which skips one level of the chain. Linters such as ESLint's preserve-caught-error rule can flag catch blocks that throw a new error without passing the caught one as cause.
What cause can hold
cause accepts any value: an Error, a string, a number, or a plain object. Usually it should be the caught error, unchanged. JavaScript lets code throw any value, so the caught value is not always an Error, and cause takes it as is.
try {
throw 'legacy string failure'; // some old library does this
} catch (cause) {
const err = new Error('Import step failed', { cause });
console.log(typeof err.cause); // 'string'
}Some teams also use cause to attach structured context, such as { cause: { userId, attempt } }. The spec allows this, and MDN's documentation shows it as one use. If you do it, be consistent. Code that walks the chain must then handle causes that are not Error objects, which the chapter on walking the cause chain addresses. If you only need context fields, a custom property on a custom class is often clearer.
How runtimes display cause
You do not need to print cause yourself while debugging. Node.js prints it as part of the error. The output looks roughly like this:
Error: Invalid PORT setting
at readPortSetting (file:///app/port.js:12:11)
... {
[cause]: RangeError: Port out of range: 99999
at parsePort (file:///app/port.js:4:36)
...
}Both stack traces appear, so you can see where the wrap happened and where the failure started. Chromium and Firefox devtools also show cause when you expand a logged error. JSON.stringify does not include cause, and neither does String(err). The chapter on logging and serializing errors deals with that.
Runtime support and older environments
cause is supported in Node.js 16.9+, Chrome 93+, Firefox 91+, and Safari 15+. Older runtimes accept the second argument and ignore it, so the code runs but err.cause is undefined. If you must support such environments, feature-detect it and define the property yourself:
const supportsCause = 'cause' in new Error('', { cause: 1 });
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'AppError';
if (!supportsCause && options && 'cause' in options) {
Object.defineProperty(this, 'cause', {
value: options.cause,
writable: true,
enumerable: false,
configurable: true,
});
}
}
}
const e = new AppError('outer', { cause: new Error('inner') });
console.log(e.cause.message); // 'inner'In TypeScript, the options parameter type is available when your lib setting includes es2022 or later.
Exercises
Exercise
A teammate writes class StorageError extends Error { constructor(msg) { super(msg); this.name = 'StorageError'; } } and then throw new StorageError('Write failed', { cause: err }). What is the thrown error's cause, and how do you fix the class?
Show answer
cause is undefined, because the constructor never passes the options object to super, so Error never sees it. Fix it by accepting and forwarding options: constructor(msg, options) { super(msg, options); this.name = 'StorageError'; }.
Exercise
What does new Error('Fetch failed', err).cause evaluate to when err is new Error('timeout')? What if err was created as new Error('timeout', { cause: 'DNS' })?
Show answer
In the first case it is undefined, because err is treated as the options object and has no cause property. In the second case it is the string 'DNS', because the constructor reads err.cause. That silently skips the timeout error. The correct call is new Error('Fetch failed', { cause: err }).
Exercise
Write a function readJson(text) that returns JSON.parse(text), but on failure throws a TypeError with the message "Invalid JSON input" and the original SyntaxError as its cause. Verify that err.cause instanceof SyntaxError is true.
Show answer
function readJson(text) { try { return JSON.parse(text); } catch (cause) { throw new TypeError('Invalid JSON input', { cause }); } } Then try { readJson('{bad'); } catch (err) { console.log(err instanceof TypeError, err.cause instanceof SyntaxError); } prints true true.