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.

JavascriptResilience

Code

javascriptsnippet
30 lines
// 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 number

How 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 early throw when 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

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.