JS 堆栈跟踪

发布时间 2023-10-12 17:03:25作者: 地铁程序员

堆栈跟踪 API
V8 中抛出的所有内部错误在创建时都会捕获堆栈跟踪。可以通过非标准error.stack属性从 JavaScript 访问此堆栈跟踪。V8 还具有各种钩子,用于控制堆栈跟踪的收集和格式化方式,以及允许自定义错误也收集堆栈跟踪。本文档概述了 V8 的 JavaScript 堆栈跟踪 API。


function getStack(error) {
  const orig = Error.prepareStackTrace;
  Error.prepareStackTrace = (_, stack) => stack;
  const stack = error.stack;
  Error.prepareStackTrace = orig;
  return stack;
}

function trace() {
  try {
    throw new Error('stack');
  }
  catch (error) {
    console.log(getStack(error)[0].getFunctionName());
  }
}

function b() {
  trace();
}

function a() {
  b();
}

a()


// 参考文档:堆栈跟踪 API:(https://v8.dev/docs/stack-trace-api)