Sub topic 10
Walking the Cause Chain to the Root Failure
This chapter assumes you already know how to pass { cause: err } to the Error constructor and how to wrap errors at layer boundaries. It also uses generator functions (function* and yield). You only need to know that a generator produces values one at a time and works with for...of.
When every layer of an application wraps the error it caught, you end up with a linked list of errors. The top error describes what the user tried to do, such as "Server failed to start". Each cause points one level deeper, and the last link is the low-level failure that started it all, such as a missing file or a JSON syntax error. This chapter shows how to walk that list safely, find the root failure, search it for a specific error, and print it in a readable form.
What a Cause Chain Looks Like
A cause chain is the sequence you get by starting at an error and following .cause until there is nothing left to follow.
You can build the same chain by hand to experiment with:
const low = new SyntaxError('Unexpected token } in JSON at position 42');
const mid = new Error('Failed to load config from ./app.json', { cause: low });
const top = new Error('Server failed to start', { cause: mid });
console.log(top.cause === mid); // true
console.log(top.cause.cause === low); // true
console.log(low.cause); // undefinedWriting top.cause.cause by hand only works when you already know how deep the chain is. Real chains can have any length, so you need a loop.
A Safe Chain Walker
The naive loop is while (err) { ...; err = err.cause; }. It has two problems:
- A cause does not have to be an
Error. Code can pass a string, a number, or a plain object as the cause. Reading.causefrom a string givesundefined, which happens to be harmless, but reading it from a plain object could pick up an unrelatedcausefield. - A chain can contain a cycle. The
causeproperty is writable, so a bug, or deliberately hostile code, can makea.cause = bandb.cause = a. The naive loop never ends.
This generator handles both:
function* causeChain(err) {
const seen = new Set();
let current = err;
while (current !== undefined && !seen.has(current)) {
seen.add(current);
yield current;
current = current instanceof Error ? current.cause : undefined;
}
}
function rootCause(err) {
let last;
for (const e of causeChain(err)) last = e;
return last;
}The generator works like this:
- It yields the current value, starting with the error you passed in.
- If that value is an
Error, it moves to itscause. If not, it treats the value as the end of the chain, so a non-Error cause is reported once and never looked into. - It stops when the next value is
undefined(no cause), or when the value is already in theseenset (a cycle).
rootCause keeps the last value the generator produced. Because the generator yields the starting error first, an error with no cause is its own root cause.
Run it against the chain from earlier:
for (const e of causeChain(top)) {
console.log(`${e.name}: ${e.message}`);
}
// Error: Server failed to start
// Error: Failed to load config from ./app.json
// SyntaxError: Unexpected token } in JSON at position 42
console.log(rootCause(top) === low); // trueEdge Cases the Walker Handles
| Situation | What `causeChain` yields | What `rootCause` returns |
|---|---|---|
| Error with no cause | Only the error | The error itself |
| Cause is a string, such as `'timeout'` | The errors, then `'timeout'` | `'timeout'` |
| Cause is a plain object `{ code: 1, cause: x }` | The errors, then the object; `x` is ignored | The object |
| Cycle: `a.cause = b`, `b.cause = a` | `a`, then `b`, then stops | `b` |
| Cause is `null` | The errors, then `null` | `null` |
| Input is `undefined` | Nothing | `undefined` |
The null row deserves attention. { cause: null } is legal, and the walker reports null as a final link because it only checks for undefined. If your code treats null as "no cause", change the loop condition to current != null, which excludes both null and undefined. Decide which rule you want and use it everywhere.
Here is the cycle case, which shows the seen set in action:
const a = new Error('a');
const b = new Error('b', { cause: a });
a.cause = b; // creates a cycle
console.log([...causeChain(a)].map((e) => e.message)); // [ 'a', 'b' ]
console.log(rootCause(a).message); // 'b'Searching the Chain
Often you do not need the root. You need to know whether a particular kind of failure happened anywhere below. A retry policy might ask whether any link is a network reset. An HTTP handler might ask whether any link is a NotFoundError so it can answer with 404 even though a service layer wrapped it.
Because causeChain is a generator, a search can stop at the first match without walking the rest:
function findCause(err, ErrorClass) {
for (const e of causeChain(err)) {
if (e instanceof ErrorClass) return e;
}
return undefined;
}
function findCode(err, code) {
for (const e of causeChain(err)) {
if (e instanceof Error && e.code === code) return e;
}
return undefined;
}Node.js system errors carry a code string such as 'ENOENT' or 'ECONNRESET', so findCode works well with wrapped I/O failures. This complete Node.js script (save it as walk.mjs) reads a file that does not exist:
import { readFile } from 'node:fs/promises';
function* causeChain(err) {
const seen = new Set();
let current = err;
while (current !== undefined && !seen.has(current)) {
seen.add(current);
yield current;
current = current instanceof Error ? current.cause : undefined;
}
}
function findCode(err, code) {
for (const e of causeChain(err)) {
if (e instanceof Error && e.code === code) return e;
}
return undefined;
}
async function loadConfig(path) {
try {
return JSON.parse(await readFile(path, 'utf8'));
} catch (err) {
throw new Error(`Failed to load config from ${path}`, { cause: err });
}
}
async function startServer() {
try {
await loadConfig('./does-not-exist.json');
} catch (err) {
throw new Error('Server failed to start', { cause: err });
}
}
try {
await startServer();
} catch (err) {
const missing = findCode(err, 'ENOENT');
if (missing) {
console.log(`Missing file: ${missing.path}`);
} else {
throw err;
}
}
// Missing file: ./does-not-exist.jsonThe top-level handler never mentions loadConfig, but it can still react to the specific low-level failure. If nothing matches, it rethrows, so unexpected errors stay visible.
Printing the Chain for Humans
Recent Node.js versions already show causes when you console.log an error, nesting each one under a [cause] label. Browsers vary, and plain-text log lines often show only err.message. A small formatter makes the chain readable everywhere:
function formatChain(err) {
return [...causeChain(err)]
.map((e, i) => {
const label = e instanceof Error
? `${e.name}: ${e.message}`
: `(non-Error cause) ${String(e)}`;
const prefix = i === 0 ? '' : `${' '.repeat(i)}caused by `;
return prefix + label;
})
.join('\n');
}
console.log(formatChain(top));
// Error: Server failed to start
// caused by Error: Failed to load config from ./app.json
// caused by SyntaxError: Unexpected token } in JSON at position 42This output is meant for people reading a log. Turning a chain into structured JSON for a log pipeline is a separate problem, covered in the serialization chapter.
Common Mistakes
- Walking with
while (err)and no cycle check. One bad assignment hangs the process. Always track visited links. - Reading
.causeoff non-Error values. A plain object with acausefield is not part of the chain. Only follow.causeonErrorinstances. - Assuming the root is an
Error.rootCausemay return a string, a number, ornull. Check withinstanceof Errorbefore you read.messageor.stack. - Expecting the walker to enter
AggregateError. A cause chain is linear. AnAggregateErrorholds its sub-errors in anerrorsarray, not incause, socauseChaintreats it as one link. If you need the inner failures, walkerrorsseparately. - Dropping the top error after finding the root. The root explains the mechanism, and the outer errors explain the context. Log the whole chain and branch on whichever link you need.
Exercise
An error is created with const e = new Error('outer', { cause: 42 }). What does [...causeChain(e)] produce, and what does rootCause(e) return? Why doesn't the walker try to read (42).cause?
Show answer
It produces [e, 42], and rootCause(e) returns 42. After yielding 42, the generator checks 42 instanceof Error, which is false, so it sets current to undefined and stops. It never reads a cause property from a non-Error value.
Exercise
Write a function hasCause(err, predicate) that returns true if any link in the chain, including err itself, satisfies predicate. Use it to check whether a chain contains an error whose code is 'ECONNRESET'.
Show answer
function hasCause(err, predicate) { for (const e of causeChain(err)) { if (predicate(e)) return true; } return false; } Usage: hasCause(err, (e) => e instanceof Error && e.code === 'ECONNRESET'). The loop returns as soon as one link matches, and the cycle check in causeChain guarantees it ends.
Exercise
You want formatChain to print at most 10 links and then the line ... (chain truncated). Where would you add the limit, and why is a depth limit useful even though causeChain already detects cycles?
Show answer
Count links in a loop over causeChain(err) and break once 10 have been collected, then add the truncation line if more remained. Breaking out of for...of closes the generator. Cycle detection only stops repeats. A very long chain with no cycle, for example one built by a retry loop that wraps on every attempt, would still produce a huge log entry, and a depth limit keeps output bounded.