Sub topic 9
Adding Context with the cause Option
This chapter assumes you can write try/catch blocks, throw errors, define a class that extends Error, and check errors with instanceof. Those topics come in earlier chapters. Here the focus is one narrow problem: how to add meaning to an error without losing the original one.
The Problem: Low-Level Errors Lack Context
Errors usually start deep in your code, in a parser, a file read, or a network call. By the time they reach the code that reports them, the original message often says what broke but not why that mattered.
Suppose a settings loader fails. The raw error might be SyntaxError: Unexpected end of JSON input. That is accurate, but a reader of the logs can't tell which file was being parsed or what the program was trying to do.
Before ES2022, developers had three imperfect choices:
- Rethrow the original error. The type and stack survive, but no context gets added.
- Throw a new error with a better message. The context improves, but the original error and its stack are lost.
- Glue the old message into the new one, as in
new Error('Settings failed: ' + err.message). Part of the text survives, but the original stack, type, and any custom fields are lost.
The cause option solves this. You create a new, descriptive error and attach the original one to it.
The Basic Syntax
The Error constructor accepts a second argument, an options object. If that object has a cause property, the new error gets a cause property with the same value.
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Could not parse settings file', { cause: err });
}
}
try {
parseSettings('{ "theme": ');
} 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 error text
console.log(err.cause instanceof SyntaxError); // true
}The outer error explains what the program was doing. The inner error still holds the exact failure, with its own type and stack trace. Nothing is lost.
All the built-in error constructors accept the option: TypeError, RangeError, SyntaxError, and the others. AggregateError takes it as its third argument, because its first argument is the list of errors.
const agg = new AggregateError(
[new Error('a'), new Error('b')],
'Several tasks failed',
{ cause: 'batch-17' }
);
console.log(agg.cause); // batch-17How cause Behaves Internally
The cause property has a few details that matter when you write tools that inspect errors.
const plain = new Error('no options');
console.log('cause' in plain); // false
const explicit = new Error('explicit undefined', { cause: undefined });
console.log('cause' in explicit); // true
console.log(explicit.cause); // undefined
const withCause = new Error('outer', { cause: new Error('inner') });
console.log(Object.keys(withCause)); // []
console.log(Object.getOwnPropertyDescriptor(withCause, 'cause').enumerable); // false
const anything = new Error('odd cause', { cause: { code: 42 } });
console.log(anything.cause.code); // 42These results come from the following rules:
| Rule | Consequence |
|---|---|
| The property is created only if the options object has a `cause` key | `err.cause === undefined` cannot tell you whether a cause was given; use `'cause' in err` |
| The property is an own, non-enumerable data property | `Object.keys`, spread, and `JSON.stringify` skip it |
| The value can be anything | Code that walks a chain must not assume every cause is an `Error` |
| The property is writable | You can set `err.cause` by hand, which is useful on older engines |
Building a Chain Across Layers
Real programs have layers, and each layer can add its own context. Every wrap adds one link to the chain.
Custom error classes support cause as long as they pass the options object on to super.
class ConfigError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ConfigError';
}
}
class StartupError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'StartupError';
}
}
function loadConfig(fileName, text) {
try {
return JSON.parse(text);
} catch (err) {
throw new ConfigError(`Could not load ${fileName}`, { cause: err });
}
}
function startApp() {
try {
const config = loadConfig('config.json', '{ "port": ');
return config;
} catch (err) {
throw new StartupError('App failed to start', { cause: err });
}
}
try {
startApp();
} catch (err) {
console.log(err.name); // StartupError
console.log(err.cause.name); // ConfigError
console.log(err.cause.cause.name); // SyntaxError
}Forgetting to pass options to super is the most common mistake here. If the constructor calls super(message) alone, the cause is silently dropped and the chain ends early.
If your class needs extra fields, take them from the same options object. The Error constructor reads only the cause key and ignores the rest.
class QueryError extends Error {
constructor(message, options = {}) {
super(message, options);
this.name = 'QueryError';
this.query = options.query;
}
}
const e = new QueryError('Lookup failed', { cause: new Error('timeout'), query: 'users' });
console.log(e.query, e.cause.message); // users timeoutReading the Chain
Printing It
Node.js and current browser consoles print the cause chain when you log an error object. Node shows nested [cause] entries, and browser devtools show the linked errors. The exact format differs between environments, so if you need consistent output, for example in log files, format the chain yourself.
function formatErrorChain(err) {
const lines = [];
const seen = new Set();
let current = err;
let depth = 0;
while (current !== undefined && current !== null && !seen.has(current)) {
seen.add(current);
const label = current instanceof Error
? `${current.name}: ${current.message}`
: String(current);
lines.push(`${' '.repeat(depth)}${depth > 0 ? 'caused by ' : ''}${label}`);
current = current instanceof Error ? current.cause : undefined;
depth++;
}
return lines.join('\n');
}
const inner = new SyntaxError('Unexpected end of JSON input');
const middle = new Error('Could not load config.json', { cause: inner });
const outer = new Error('App failed to start', { cause: middle });
console.log(formatErrorChain(outer));
// Error: App failed to start
// caused by Error: Could not load config.json
// caused by SyntaxError: Unexpected end of JSON inputThe seen set guards against cycles. Because cause is writable, code can create a loop such as a.cause = b; b.cause = a, and a naive while loop over that would never end.
Finding a Specific Cause
Wrapping has a cost: the outer error now has a different type. A caller that checked err instanceof SyntaxError will stop matching once you wrap. When a caller needs to react to something deep in the chain, search the chain instead of checking only the top.
function findCause(err, Type) {
const seen = new Set();
let current = err;
while (current instanceof Error && !seen.has(current)) {
if (current instanceof Type) return current;
seen.add(current);
current = current.cause;
}
return undefined;
}
const wrapped = new Error('Request failed', { cause: new RangeError('Port out of range') });
const rangeErr = findCause(wrapped, RangeError);
console.log(rangeErr ? rangeErr.message : 'not found'); // Port out of rangeSerializing It
To send a chain to a logging service, convert it into plain data yourself.
function serializeError(err, seen = new Set()) {
if (!(err instanceof Error)) return err;
if (seen.has(err)) return '[Circular]';
seen.add(err);
return {
name: err.name,
message: err.message,
stack: err.stack,
...('cause' in err ? { cause: serializeError(err.cause, seen) } : {}),
};
}
const failure = new Error('outer', { cause: new TypeError('inner') });
console.log(JSON.stringify(serializeError(failure), null, 2));The Same Pattern with async Code
cause works the same way in async functions, because await turns a rejection into a thrown error that catch receives. The async chapters cover the details. The wrapping step itself does not change.
async function fetchQuota(userId) {
throw new Error('ECONNRESET');
}
async function getQuota(userId) {
try {
return await fetchQuota(userId);
} catch (err) {
throw new Error(`Failed to load quota for user ${userId}`, { cause: err });
}
}
getQuota(7).catch((err) => {
console.log(err.message); // Failed to load quota for user 7
console.log(err.cause.message); // ECONNRESET
});When to Wrap and When Not To
Wrap an error when you cross a boundary and can say something the lower layer could not. Good examples are which file, which user, which step of a job, or which business operation was running.
Avoid wrapping in these cases:
- You have nothing new to say. A wrapper that reads "Error in function x" only adds noise. Rethrow the original instead.
- Callers depend on the original type. Either keep the type, document the new one, or give callers a helper such as
findCause. - The outer message would repeat the inner message. Keep the messages separate. The chain already shows both, and repeating the text makes logs harder to read.
Compatibility
The cause option is part of ES2022. It is supported in Chrome 93+, Firefox 91+, Safari 15+, and Node.js 16.9+. Older engines ignore the second argument without throwing, so the cause just disappears. If you have to support those engines, assign the property directly: const e = new Error(msg); e.cause = err;. Note that this creates an enumerable property, unlike the built-in option. In TypeScript, the option's type is available once lib includes es2022.
Exercise
A class is defined as class DbError extends Error { constructor(msg, opts) { super(msg); this.name = 'DbError'; } }. Code throws new DbError('Insert failed', { cause: original }), and a handler logs err.cause. What does it print, and how do you fix it?
Show answer
It prints undefined, because the constructor never passes opts to super, so Error never sees the cause key and creates no cause property. Change the call to super(msg, opts).
Exercise
After you wrap JSON parse failures in new ConfigError('Bad config', { cause: err }), an existing caller's check if (err instanceof SyntaxError) stops matching. Why, and what are two ways to fix it?
Show answer
The thrown object is now a ConfigError, and the SyntaxError is only its cause, so instanceof SyntaxError on the outer error is false. You can change the caller to search the chain (for example with findCause(err, SyntaxError)), or change the caller to check for ConfigError, which is now the documented error for this operation.
Exercise
What do 'cause' in new Error('a'), 'cause' in new Error('a', { cause: undefined }), and JSON.stringify(new Error('a', { cause: 1 })) return?
Show answer
false, true, and "{}". The property exists only when the options object has a cause key, even if the value is undefined, and JSON.stringify skips it because it is non-enumerable, just like message and stack.