← 中文资源

简体中文版本

用 Error.captureStackTrace 裁掉内部校验辅助栈帧

向 Error.captureStackTrace 传入断言或校验辅助函数引用,自动从堆栈中裁剪内部包装帧,让错误堆栈首行直接定位到调用方真实源码位置。

阅读英文原文

运行结果

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

frames: V | a | l
helper hidden: true | caller shown: true

实现说明

用 Error.captureStackTrace 裁掉内部校验辅助栈帧以类 ValidationError和函数 assertValidPort、loadServerConfig为骨架。 失败路径是显式的——守卫条件成立就抛出 ValidationError。

使用要点

  • 没有锁文件条目,没有版本钉死——除了运行时,文件什么都不需要。
  • 直接运行文件,输出会带上标签,比如 frames:、helper hidden:——输出的每一行都能指回产生它的那次调用。

常见问题

坏输入有失败路径吗?

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

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 assertValidPort、loadServerConfig。

签名一览:function assertValidPort(port)

核心语句

.map((line) => line.trim().replace(/\s+\(.*\)$/, '').replace(/file:\/\/\/.*\//, ''));
throw new ValidationError(`invalid port: ${port}`, assertValidPort);
Error.captureStackTrace(this, boundaryFn ?? ValidationError);

代码示例

class ValidationError extends Error {
  constructor(message, boundaryFn) {
    super(message);
    this.name = 'ValidationError';
    // Exclude boundaryFn and internal frames above it from the captured stack
    if (typeof Error.captureStackTrace === 'function') {
      Error.captureStackTrace(this, boundaryFn ?? ValidationError);
    }
  }
}

function assertValidPort(port) {
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
    throw new ValidationError(`invalid port: ${port}`, assertValidPort);
  }
}

function loadServerConfig(port) {
  assertValidPort(port);
}

try {
  loadServerConfig(70000);
} catch (err) {
  const topFrames = err.stack
    .split('\n')
    .slice(0, 3)
    .map((line) => line.trim().replace(/\s+\(.*\)$/, '').replace(/file:\/\/\/.*\//, ''));
  console.log('frames:', topFrames.join(' | '));
  console.log('helper hidden:', !err.stack.includes('assertValidPort'), '| caller shown:', err.stack.includes('loadServerConfig'));
}