Sub topic 10
Walking the Cause Chain to the Root Failure
This chapter assumes you know how to wrap an error with the cause option and rethrow it at a layer boundary, as covered in the previous chapters. It also uses generator functions (function* and yield) and for...of loops.
When each layer wraps the error from the layer below, you get a linked list of errors. The top error describes the failed operation, such as "Could not load user 42". The bottom error usually holds the detail you need to fix the problem, such as a refused connection. Walking the chain means following cause from the top error down to that bottom error.
A safe chain walker
A plain while (err.cause) loop works on well-behaved chains, but it breaks in two ways that you will meet in practice:
- A
causecan be any value, such as a string, a number, or a plain object. Reading.causefrom a string returnsundefinedwithout an error, but a value that isn't an Error has no chain of its own to follow. - A chain can contain a cycle when code sets
a.cause = bandb.cause = a. A naive loop never ends.
The generator below handles both cases. It yields each link, stops at a value that isn't an Error, and tracks visited errors in a Set so a cycle ends the walk.
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;
}
const low = new Error('connect ECONNREFUSED 127.0.0.1:5432');
const mid = new Error('Query failed: SELECT * FROM users', { cause: low });
const top = new Error('Could not load user 42', { cause: mid });
for (const e of causeChain(top)) {
console.log(e.message);
}
// Could not load user 42
// Query failed: SELECT * FROM users
// connect ECONNREFUSED 127.0.0.1:5432
console.log(rootCause(top).message); // 'connect ECONNREFUSED 127.0.0.1:5432'A generator works well here because callers decide how much of the chain to read. Logging code can print every link. A retry check can stop at the first match.
Searching the chain for a specific class
Often you don't need the root. You only need to know whether some link in the chain is a particular kind of error. Because causeChain yields values lazily, a search stops as soon as it finds a match:
class TimeoutError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'TimeoutError';
}
}
function findCause(err, ErrorClass) {
for (const e of causeChain(err)) {
if (e instanceof ErrorClass) return e;
}
return undefined;
}
const wrapped = new Error('Sync job failed', {
cause: new Error('Fetch failed', { cause: new TimeoutError('No response after 5000 ms') }),
});
const timeout = findCause(wrapped, TimeoutError);
console.log(timeout?.message); // 'No response after 5000 ms'With this pattern, a top-level handler can decide to retry on timeouts, however many layers have wrapped them.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `while (err.cause) err = err.cause` | Never ends on a cyclic chain | Track visited errors in a `Set` |
| Assuming the root is an Error | `rootCause(err).message` is `undefined` for a string cause | Check `instanceof Error` before reading Error properties |
| Checking only the top error with `instanceof` | Misses a wrapped `TimeoutError` | Search the chain with `findCause` |
Exercise
Given const a = new Error('a'); const b = new Error('b', { cause: a }); a.cause = b;, what does [...causeChain(b)].map(e => e.message) return, and why doesn't it loop forever?
Show answer
It returns ['b', 'a']. After yielding a, the walker moves to a.cause, which is b. b is already in the seen set, so the loop condition fails and the generator finishes.
Exercise
What does rootCause(new Error('outer', { cause: 'disk full' })) return?
Show answer
The string 'disk full'. The walker yields the outer error, moves to its cause, and yields the string. A string is not an Error, so the next step sets current to undefined and the walk stops with the string as the last value yielded.