Sub topic 11
How the cause Property Is Defined
This chapter assumes you already know how to pass { cause } to the Error constructor and how to wrap errors at layer boundaries, both covered in earlier chapters. You should also be comfortable with property descriptors (Object.getOwnPropertyDescriptor) and the difference between own and inherited properties.
The cause option looks like a simple constructor argument, but the specification defines exactly when the property is created and what kind of property it is. Those details explain several things that surprise people: JSON.stringify drops the cause, err.cause === undefined is not a reliable test, and assigning cause after construction behaves differently from passing it in.
The Algorithm Behind the Option
ES2022 added an abstract operation called InstallErrorCause. Every error constructor runs it: Error, the built-in subtypes such as TypeError and RangeError, and AggregateError. Its steps are short:
- If the
optionsargument is an object, andoptionshas a property named"cause", continue. Otherwise do nothing. - Read the value with an ordinary property get:
options.cause. - Define an own data property named
"cause"on the new error. It is writable, configurable, and non-enumerable.
Each step has a consequence you can observe.
Consequence 1: Presence Depends on the Key, Not the Value
Step 1 uses a "has property" check, which works like the in operator. It does not check whether the value is undefined. So there are three distinct states:
const none = new Error('a');
const explicitUndefined = new Error('b', { cause: undefined });
const real = new Error('c', { cause: new Error('root') });
console.log(Object.hasOwn(none, 'cause')); // false
console.log(Object.hasOwn(explicitUndefined, 'cause')); // true
console.log(Object.hasOwn(real, 'cause')); // true
console.log(none.cause); // undefined
console.log(explicitUndefined.cause); // undefinednone.cause and explicitUndefined.cause both read as undefined, but only one of them has the property. If your code needs to know whether a caller supplied a cause at all, use Object.hasOwn(err, 'cause') or 'cause' in err. Error.prototype has no cause property, so for normal errors the two checks give the same answer.
This matters when you forward options through a helper:
function wrap(message, original) {
// Always creates a cause property, even when original is undefined
return new Error(message, { cause: original });
}
function wrapIfPresent(message, original) {
// Only creates cause when there is something to attach
return original === undefined
? new Error(message)
: new Error(message, { cause: original });
}
console.log('cause' in wrap('x')); // true
console.log('cause' in wrapIfPresent('x')); // falseEither version is acceptable. Pick one and apply it consistently, because tools that print errors often show an empty [cause]: undefined line for the first style.
Consequence 2: Non-Objects Are Ignored, Inherited Keys Count
Step 1 only accepts objects. If you pass a string or number as the second argument, the constructor ignores it without throwing:
const e1 = new Error('oops', 'not an options object');
console.log('cause' in e1); // falseThis sometimes happens when someone mistakes the second argument for a file name. Firefox's non-standard signature new Error(message, fileName, lineNumber) is one source of that confusion.
The "has property" check also walks the prototype chain of the options object. An inherited cause is installed just like an own one, and a getter is called exactly once:
const defaults = { cause: 'inherited cause' };
const options = Object.create(defaults);
console.log(new Error('x', options).cause); // 'inherited cause'
let reads = 0;
const lazy = {
get cause() {
reads += 1;
return new Error('computed');
},
};
const e2 = new Error('y', lazy);
console.log(reads); // 1
console.log(e2.cause.message); // 'computed'The value is copied at construction time. Changing options.cause later does not affect the error.
Consequence 3: Any Value Can Be a Cause
Step 2 does not validate the value. Strings, numbers, null, plain objects, and even the error itself are all accepted:
console.log(new Error('a', { cause: null }).cause); // null
console.log(new Error('b', { cause: { code: 42 } }).cause); // { code: 42 }
const self = new Error('c');
const loop = new Error('d', { cause: self });
self.cause = loop; // a cycle is allowedThis is deliberate, because JavaScript lets you throw any value and a catch block can receive anything. The cost moves to code that reads causes. A cause chain walker must stop at non-Error values and guard against cycles, as the generator in the earlier chain-walking chapter does.
Consequence 4: The Property Is Non-Enumerable
Step 3 creates the property with the same attributes as message and stack:
const err = new Error('outer', { cause: new Error('inner') });
console.log(Object.getOwnPropertyDescriptor(err, 'cause'));
// { value: Error: inner ..., writable: true, enumerable: false, configurable: true }
console.log(Object.keys(err)); // []
console.log(JSON.stringify(err)); // '{}'
console.log({ ...err }); // {}
console.log(Object.getOwnPropertyNames(err)); // [ 'stack', 'message', 'cause' ]The stack entry appears in V8 (Node.js and Chromium). Other engines may store stack differently.
Non-enumerability keeps cause consistent with the other built-in error properties and keeps it out of for...in loops and Object.keys. It also means anything based on enumeration drops it: JSON.stringify, object spread, Object.assign, and many logging libraries. Node's console.log and util.inspect do display it, as a [cause] entry, because they look at non-enumerable properties on errors specifically. A later chapter builds a serializer that handles this.
Consequence 5: Assigning Later Is Not the Same
Because cause is writable and configurable, you can change it after construction. What you get depends on whether the property already exists:
const a = new Error('a', { cause: 'original' });
a.cause = 'replaced';
console.log(Object.getOwnPropertyDescriptor(a, 'cause').enumerable); // false
const b = new Error('b');
b.cause = 'added later';
console.log(Object.getOwnPropertyDescriptor(b, 'cause').enumerable); // true
console.log(JSON.stringify(b)); // '{"cause":"added later"}'Plain assignment to a missing property creates a normal enumerable property. Errors built this way serialize differently from errors built with the option. If you must attach a cause after construction, for example in code that predates ES2022, define it with matching attributes:
function setCause(err, cause) {
Object.defineProperty(err, 'cause', {
value: cause,
writable: true,
enumerable: false,
configurable: true,
});
return err;
}Consequence 6: Subclasses Must Forward Options
InstallErrorCause runs inside the Error constructor. A subclass gets a cause only if it passes options through to super:
class DropsCause extends Error {
constructor(message) {
super(message); // options never reach Error
this.name = 'DropsCause';
}
}
class KeepsCause extends Error {
constructor(message, options) {
super(message, options);
this.name = 'KeepsCause';
}
}
const root = new Error('root');
console.log('cause' in new DropsCause('x', { cause: root })); // false
console.log(new KeepsCause('x', { cause: root }).cause === root); // trueDropsCause fails silently. No error is thrown, and the cause just disappears. This is the most common reason a wrapped error arrives in logs without its origin.
AggregateError takes options as its third argument, after the iterable of errors and the message:
const agg = new AggregateError([new Error('a')], 'batch failed', { cause: 'retry limit' });
console.log(agg.cause); // 'retry limit'Summary of Attributes
| Situation | Own `cause`? | Enumerable? |
|---|---|---|
| `new Error(msg)` | No | Not applicable |
| `new Error(msg, { cause: undefined })` | Yes | No |
| `new Error(msg, { cause: x })` | Yes | No |
| `new Error(msg, 'string')` | No | Not applicable |
| `err.cause = x` on an error without one | Yes | Yes |
| `err.cause = x` on an error that has one | Yes | No |
| Subclass that omits `options` in `super` | No | Not applicable |
Exercises
Exercise
What do these three lines print, and why? console.log('cause' in new Error('a', { cause: undefined })); console.log('cause' in new Error('b', 'oops')); console.log('cause' in new Error('c', Object.create({ cause: 1 })));
Show answer
They print true, false, true. The first options object has a "cause" key, so the property is installed even though its value is undefined. The second argument in the second line is a string, not an object, so it is ignored. The third options object inherits "cause" from its prototype, and the has-property check follows the prototype chain, so the property is installed with value 1.
Exercise
A legacy helper does const e = new Error(msg); e.cause = original; return e;. Your logger uses JSON.stringify and suddenly shows a "cause" field for these errors but not for errors created with { cause }. Explain the difference and fix the helper.
Show answer
Assigning to a missing property creates an ordinary enumerable property, so JSON.stringify includes it. The constructor option defines cause as non-enumerable, so JSON.stringify skips it. Fix the helper by passing the option, return new Error(msg, { cause: original });, or by using Object.defineProperty with enumerable: false. Then handle causes explicitly in the logger instead of relying on enumeration.
Exercise
A teammate's class ApiError extends Error { constructor(message, status) { super(message); this.status = status; } } is called as new ApiError('failed', 500, { cause: err }). Why is the cause missing, and what signature would you use instead?
Show answer
The constructor never forwards a third argument to super. The cause option is only processed inside the Error constructor, so it is lost without an error being thrown. Use constructor(message, status, options) { super(message, options); this.name = 'ApiError'; this.status = status; }. Alternatively, put status into the options object and still pass that object to super.