Sub topic 3
Walking the Cause Chain to the Root Failure
This chapter assumes you can already write a custom error class and wrap errors with { cause }. It covers what to do with those errors after they are thrown: inspecting them, combining them, and logging them.
Walking the Cause Chain
Each wrapped error points to the error below it, so you can follow the cause links down to the original failure. The walker below also guards against cycles, because nothing stops code from creating a.cause = b and b.cause = a.
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('ECONNRESET');
const high = new Error('Failed to load user', { cause: low });
console.log(rootCause(high).message); // 'ECONNRESET'How cause Is Defined
The constructor creates cause only when the options object has a cause key. Passing { cause: undefined } still creates the property. When it exists, cause is an own property and it is non-enumerable, so Object.keys(err) does not list it. A cause can be any value, including a string, which is why the walker stops when it reaches something that is not an Error.
Several Failures at Once
AggregateError holds a list of errors in its errors property. Promise.any rejects with one when every input promise rejects.
const failures = [new Error('a'), new Error('b')];
const agg = new AggregateError(failures, '2 requests failed');
console.log(agg.errors.length); // 2Serializing for Logs
JSON.stringify skips message, stack, and cause because they are non-enumerable. It also skips name, which is inherited from the prototype. A helper has to copy these fields by hand:
function serializeError(err) {
if (!(err instanceof Error)) return err;
return {
...err,
name: err.name,
message: err.message,
stack: err.stack,
cause: serializeError(err.cause),
};
}
const e = new Error('outer', { cause: new Error('inner') });
console.log(JSON.stringify(e)); // '{}'
console.log(JSON.stringify(serializeError(e), null, 2));Stack Traces and ES5 Pitfalls
V8, the engine in Node.js and Chromium, provides the non-standard Error.captureStackTrace(this, MyError). Calling it hides the constructor's own frames from the stack trace. Wrap the call in a typeof check so it does nothing on other engines.
Code compiled to an ES5 target does not set up the prototype chain correctly when it subclasses Error, so instanceof returns false. The fix is to add Object.setPrototypeOf(this, new.target.prototype) right after super(). A better fix is to compile to ES2015 or later.
Classes or Codes?
| Situation | Prefer |
|---|---|
| Callers branch on the error type | A custom class |
| You need extra fields (status, resource) | A custom class |
| Many fine-grained variants that are handled the same way | A generic `Error` plus a `code` field |
| The error must survive serialization across processes | A `code` field, which survives JSON |
Exercise
Why does JSON.stringify(new Error('x', { cause: 'y' })) produce '{}'?
Show answer
The message and cause properties are own but non-enumerable, and name is inherited from the prototype. JSON.stringify only includes own enumerable properties, so it outputs none of them.
Exercise
An error class works in tests but instanceof fails in the production bundle. What is the likely cause?
Show answer
The production build targets ES5, so the subclass prototype is not linked. Fix it with Object.setPrototypeOf(this, new.target.prototype) or by raising the compile target.