A user opens a profile card, the card says "Something went wrong", and your log holds one line: TypeError: Failed to fetch. Which request? Which screen? Was it the user's network or yours? The line can't say, because whatever sat between the failing fetch and the logger either rethrew the bare error or flattened it into a string.
Error.cause and AggregateError fix that without a library. The mechanics are old news, and the Node.js error handling patterns post covers them on the server. This piece starts where that one stops: a React error boundary, a TypeScript catch, a log call that serializes, and Sentry. I wrote one small harness and ran it on Node 22.23.3, 24.21.0 and 26.10.0, then in Chromium 151, Firefox 153 and WebKit 26.5 through Playwright 1.62.1, with React 19.3.1, @sentry/react 11.9.0 and tsc 7.0.2. The harness is in the repo, and npm test asserts every claim below. The @sentry/react run never touched the network, because I captured each event in beforeSend and dropped it.
Where Do You Add a Cause in a React App?
At every place that knows something the layer below can't, and nowhere else. In the harness that came to three places. The data layer knows the URL. The screen knows which card it was building. A Promise.any over two mirrors knows that both were tried.
async function getJson(url: string): Promise<unknown> {
try {
const res = await fetch(url);
if (!res.ok) {
throw new HttpError(res.status, `GET ${url} returned ${res.status}`);
}
return await res.json();
} catch (cause) {
if (cause instanceof HttpError) {
throw cause;
}
throw new HttpError(0, `GET ${url} failed`, { cause });
}
}
HttpError is a short subclass that passes its options argument to super. The screen adds the second link. React's docs say boundaries don't catch errors from asynchronous code, so the screen keeps the failure in state and throws it from render, which the boundary does catch:
function Profile() {
useThrowFromRender(
() => getJson(`${DEAD}/api/user`),
(cause) => new Error('Profile card could not load', { cause }),
);
return <p>loading profile</p>;
}
DEAD is http://127.0.0.1:1, a closed port, so the real fetch rejects. That gives three links: an Error for the screen, an HttpError for the request, and the TypeError the browser raised.
The mirror screen uses Promise.any([getJson(a), getJson(b)]), which rejects with an AggregateError whose errors array holds one entry per input. I made the first input fail 30 ms after the second to check the order: the first entry in errors was still the slow one, on all three Node versions. The AggregateError message, though, is up to the engine. It was "All promises were rejected" in Chromium, "No Promise in Promise.any was resolved" in Firefox and an empty string in WebKit 26.5. The same split happens with a plain fetch failure: Failed to fetch, NetworkError when attempting to fetch resource. and Load failed. Never branch on those messages.
Here's an opinion you can argue with: don't wrap at every layer. A wrap that only renames ("Service call failed") adds a link to read and no fact. If the new message doesn't contain a URL, an id, a screen or a count, skip it and let the original travel.
What Does a React Error Boundary Receive?
The error you threw, by identity. In all three engines the boundary's componentDidCatch and React 19's root-level onCaughtError got the same object with the whole chain attached. React's reference says onCaughtError fires when a boundary catches a render error, and the info argument adds a componentStack, which neither the error nor its causes carry.
The fallback only needs to walk the chain. Because a cause is typed unknown, the walker has to survive strings, undefined and cycles:
export function causeChain(error: unknown, maxDepth = 10): unknown[] {
const chain: unknown[] = [];
const seen = new Set<unknown>();
let current: unknown = error;
while (chain.length < maxDepth && !seen.has(current)) {
chain.push(current);
seen.add(current);
if (!(current instanceof Error) || current.cause === undefined) {
break;
}
current = current.cause;
}
return chain;
}
I tested the three hostile inputs. Two errors pointing at each other made util.inspect print a [Circular *1] marker instead of looping, and the walker stopped after two links. A string cause ({ cause: 'timeout' }) came back as one non-Error link. A 50-link chain was cut at 10. Rendered through the boundary in Chromium, the profile screen showed:
Error: Profile card could not load
HttpError: GET http://127.0.0.1:1/api/user failed
TypeError: Failed to fetch (127.0.0.1:1)
Should your users see that list? I'd say no. Show the outer message, and ship the chain to your logger. The list is for a developer overlay or a support dump.
How Do You Type Error.cause in TypeScript?
As unknown, and you narrow it. The property comes from lib.es2022.error, which declares ErrorOptions and cause?: unknown. Under strict, error.cause.message is TS18046: 'error.cause' is of type 'unknown', the same code a bare catch (err) variable gets. The fix is the one you already know:
export function messageOf(error: Error): string {
return error.cause instanceof Error ? error.cause.message : String(error.cause);
}
Which lib you compile against changes the diagnostics, and I ran each one on tsc 7.0.2:
| Setting | What you get |
|---|---|
lib: es2021 | new Error(msg, { cause }) is TS2554, error.cause is TS2550 |
lib: es2021 plus es2022.error | Compiles clean |
lib: es2020 | AggregateError is TS2304, Promise.any is TS2550 |
lib: es2020 plus es2021.promise | Compiles clean |
lib: es2021, new AggregateError(e, msg, { cause }) | TS2554, since the options bag lives in es2022.error |
One more declaration quirk: AggregateError.errors is typed any[] in the library. Annotate the callback parameter ((inner: unknown) => ...) and the any stops leaking.
The trap I'd warn a teammate about is narrowing cause on a subclass. It looks harmless:
export class FetchFailure extends Error {
override cause?: TypeError;
}
On target es2022, tsc 7.0.2 accepted that with no diagnostic at all. The emitted JavaScript contains a cause; class field, which runs right after super() returns and resets the property. I constructed new FetchFailure('GET failed', { cause: new TypeError('Failed to fetch') }) and read cause back: undefined. With declare cause?: TypeError the type is just as narrow, no field is emitted, and the TypeError was still there. Compiling the plain field for es2021 emitted no field either, so the bug only exists once your target reaches ES2022. If a subclass of yours narrows cause, add one runtime assertion like the one in check-types.mjs. The compiler won't warn you.
Does JSON.stringify Keep the Cause?
No, and neither does anything else that walks enumerable keys. cause is an own property created non-enumerable, which I read straight off Object.getOwnPropertyDescriptor. message and stack aren't enumerable either. So JSON.stringify(error) returned {} for the three-link chain on every Node version and in every engine, and the AggregateError gave {} too. A subclass with public fields serialized only those fields: my HttpError came out as its name and status, with the message gone.
JSON.stringify(error) returns an empty object for an error with a three-link cause chain, so a logger that serializes errors drops exactly the part you added.
MDN's page for cause makes the same point and suggests passing structured data as the cause when a machine will read it. Copying is the fix, and the harness has a short toPlain() that walks cause, the own enumerable fields and AggregateError.errors, with a WeakSet against cycles. I asserted that its output survives JSON.stringify and keeps status: 0 and both mirror failures.
structuredClone is the other serializer you meet, because postMessage to a worker uses the same algorithm. Here the engines disagree:
| Where | Cause chain | HttpError subclass | AggregateError.errors |
|---|---|---|---|
| Node 22.23.3, 24.21.0, 26.10.0 | kept | plain Error, no status | lost, comes back as Error |
| Chromium 151 | kept | plain Error | lost, comes back as Error |
| Firefox 153 | kept | plain Error | kept, class and array |
| WebKit 26.5 (Playwright build) | outer error only, cause becomes a string | n/a | cause becomes a string |
A function anywhere in a cause object made structuredClone throw DataCloneError in Node, and a MessagePort carried the chain the same way as structuredClone. MDN's structured clone page says browsers must serialize name and message and are only expected to serialize extras such as cause, which fits the table. I ran WebKit through Playwright, not Safari itself, so treat that row as a warning to test your own target.
What Does Sentry Actually Show?
Every link, deepest first, as long as the chain is short. The Linked Errors integration follows the cause key to a default limit of five, and the event I captured matched. The three-link chain became three exception values in reverse order: the TypeError with exception_id 2, then the HttpError, then the screen's Error with exception_id 0. The mirror failure became six values. Sentry labelled the two members with an errors source naming their index and marked the AggregateError as an exception group.
Two details surprised me. First, I built an 8-link chain and sent it. The event held 6 values, so links 7 and 8 vanished without a warning. If your wrappers stack up across a hook, a service and a component, count them. Second, Sentry.ErrorBoundary didn't leave my error alone. After the catch, the same object I had thrown had a fourth link on the end of its chain, named React ErrorBoundary Error, and my own fallback rendered it. The hand-written boundary with Sentry.captureException(error) left the chain at three. That's neither good nor bad, but a fallback that prints causeChain(error) shows the extra link in one setup and not the other.
Which Browsers Have It?
All current ones, for years. MDN's compatibility data lists Error cause from Chrome 93, Firefox 91, Safari 15 and Node 16.9.0, and AggregateError and Promise.any from Chrome 85, Firefox 79, Safari 14 and Node 15, both flagged as widely available. Two notes in that data matter for debugging. The default console in Safari doesn't print the cause, and Chrome didn't before version 125, so "I can't see it in the console" on an older browser doesn't mean the cause is missing. Open the property.
Run It Yourself
cd blogs/coding-dunia/examples/error-cause-chains
npm install
npx playwright install chromium firefox webkit
npm test
npm test runs three scripts: check-node.mjs (11 assertions on logging, JSON, structuredClone, MessagePort, Promise.any order and cycles), check-types.mjs (10 tsc checks, including the emitted-JavaScript test for the class field) and run-browsers.mjs (29 assertions across the three engines). On Node 22.23.3 all three passed. On 24.21.0 and 26.10.0 I ran check-node.mjs only, and it passed. I didn't run Safari, Edge, or any mobile browser.
I would wrap errors at those three places, keep a toPlain() next to the logger and stop there. Chains of five wrappers read like diligence and behave like noise, for the same reason code smells that pass for care do. Add the cause where you know something, serialize it on purpose, and read it once in the event you actually receive.
If You're Also Dealing With...
- What else
structuredClonedrops or throws on: structuredClone vs JSON.parse(JSON.stringify()). - Errors that reach a boundary from
use(): the React 19 use() hook deep dive. - The other
unknownthat bites in components: TS2349 and TS2531 in React state. - Why
return awaitdecides whether yourcatchruns: JavaScript async/await measured.