← 中文资源

简体中文版本

Error cause 链条直达根因

new Error 的第二个参数把根因挂进 cause:包装层只补充上下文,排查时沿 cause 链向上找到最早的 TypeError,原始消息与类型都不丢失。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

outer : config invalid: port must be a number
cause : true
root  : TypeError - port must be a number

实现说明

Error cause 链条直达根因的核心是函数 readConfig、findRoot。 while (current instanceof Error && current.cause instanceof Error) 是唯一的迭代点——其余代码顺序执行一遍。TypeError、Error 是守卫的信号——在分支处抛出,任何半成品工作之前。

使用要点

  • 守卫 typeof parsed.port !== 'number' 一旦成立就走提前的 throw,把后续流程挡掉。
  • 演示输出是带标签的(outer :、cause :),每个操作都会留下自己的一行标注。

常见问题

前置条件不成立会发生什么?

代码会拒绝继续:抛出 TypeError、Error,此时状态仍可恢复。

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 文件在加载时定义 readConfig、findRoot。

签名一览:function readConfig(raw)

核心语句

throw new Error('config invalid: ' + error.message, { cause: error });
throw new TypeError('port must be a number');

代码示例

// 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);
}