Sub topic 9
Adding Context with the cause Option
This chapter assumes you can write try/catch blocks, define classes that extend Error, and check errors with instanceof. It shows how to add context to a low-level error without losing the original.
The problem: useful detail versus useful context
A low-level error describes the immediate failure, such as "Unexpected token b in JSON". It does not say what your program was trying to do. If you replace it with a clearer message, you lose the original stack trace and details. If you rethrow it unchanged, the caller gets a message that makes little sense at their level.
Since ES2022, the Error constructor takes a second argument: an options object with a cause property. The new error carries your higher-level message, and the original error stays attached to it. Node.js 16.9+ and all current browsers support this option.
Wrapping an error
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Could not parse settings file', { cause: err });
}
}
try {
parseSettings('{bad');
} catch (err) {
console.log(err.message); // 'Could not parse settings file'
console.log(err.cause.name); // 'SyntaxError'
console.log(err.cause.message); // engine-specific JSON parse message
}The outer error describes the operation that failed. err.cause is the original SyntaxError, and its own stack is unchanged. When Node.js prints an uncaught error, it prints the chain as well, with each cause shown under a [cause]: label.
Walking the cause chain
The error in cause can have its own cause, so a single error can hold a chain of several. A small loop prints the whole chain:
function describeChain(err) {
const lines = [];
let current = err;
while (current instanceof Error) {
lines.push(`${current.name}: ${current.message}`);
current = current.cause;
}
return lines.join('\n caused by ');
}
try {
try {
JSON.parse('{bad');
} catch (err) {
throw new Error('Could not parse settings file', { cause: err });
}
} catch (err) {
console.log(describeChain(new Error('App failed to start', { cause: err })));
}Passing cause through a custom class
If your subclass defines its own constructor, it has to forward the options to super. Otherwise cause is silently dropped.
class ConfigError extends Error {
constructor(message, options) {
super(message, options); // forwards { cause }
this.name = 'ConfigError';
}
}
const inner = new RangeError('port out of range');
const outer = new ConfigError('Invalid server config', { cause: inner });
console.log(outer.cause === inner); // trueCommon mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `super(message)` in a subclass | `cause` is never set | `super(message, options)` |
| `{ cause: err.message }` | The stack and type of the original error are lost | Pass the error object itself |
| Logging with `JSON.stringify(err)` | `cause`, `message`, and `stack` are non-enumerable, so they are missing from the output | Log the error directly, or build the output yourself as `describeChain` does |
| Wrapping at every layer | The chain gets long and adds no new information | Wrap only where you add context the caller needs |
Exercise
A teammate writes class DbError extends Error { constructor(msg) { super(msg); this.name = 'DbError'; } } and then throws new DbError('Query failed', { cause: err }). Why is error.cause undefined, and how do you fix it?
Show answer
The constructor accepts only msg and calls super(msg), so the options object never reaches Error. Add a second parameter and forward it: constructor(msg, options) { super(msg, options); this.name = 'DbError'; }.
Exercise
Why does JSON.stringify(new Error('outer', { cause: new Error('inner') })) return '{}'?
Show answer
message, stack, and cause are all non-enumerable own properties, and JSON.stringify includes only enumerable ones. To serialize an error chain, copy the fields you need into a plain object yourself.