Error Cause Chain Reaches The Root Failure
Preserve the root failure across rethrows with the Error cause option: outer context explains what happened while error.cause reaches the original TypeError.
Code
// Error cause(ES2022):包装错误时把根因挂进 { cause },而不是丢栈
function readConfig(raw) {
try {
const parsed = JSON.parse(raw);
if (typeof parsed.port !== 'number') {
throw new TypeError('port must be a number');
}
return parsed;
} catch (error) {
// 沿 cause 链向上回溯,就能找到根因(root failure)
throw new Error('config invalid: ' + error.message, { cause: error });
}
}
function findRoot(error) {
let current = error;
while (current instanceof Error && current.cause instanceof Error) {
current = current.cause; // 一层层剥开包装
}
return current;
}
try {
readConfig('{"port": "5432"}');
} catch (error) {
console.log('outer :', error.message);
console.log('cause :', error.cause instanceof Error);
const root = findRoot(error);
console.log('root :', root.constructor.name, '-', root.message);
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
outer : config invalid: port must be a number
cause : true
root : TypeError - port must be a numberHow the snippet works
Error Cause Chain Reaches The Root Failure keeps everything in the functions readConfig and findRoot.
Repetition is confined to while (current instanceof Error && current.cause instanceof Error) — the rest of the file is straight-line. Failure is loud: TypeError and Error aborts the current operation instead of degrading it.
What to watch for
- The guard
typeof parsed.port !== 'number'short-circuits the flow with an earlythrowwhen its condition holds.
Applying it
Entry signature: function readConfig(raw)
The run emits 3 labeled sections — outer :, cause :, root : — one per step.
Statements that matter
throw new Error('config invalid: ' + error.message, { cause: error });
throw new TypeError('port must be a number');
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.
FAQ
- What happens if the preconditions do not hold?
- The code refuses to continue: `TypeError` and `Error` is thrown while the state is still recoverable.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `readConfig`, `findRoot` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.