Error.captureStackTrace(targetObject[, constructorOpt])


targetObject 上创建一个 .stack 属性,当访问它时,会返回一个字符串,表示调用 Error.captureStackTrace() 时代码的位置。

【Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.】

const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // Similar to `new Error().stack` 

跟踪的第一行将以 ${myObject.name}: ${myObject.message} 为前缀。

【The first line of the trace will be prefixed with ${myObject.name}: ${myObject.message}.】

可选的 constructorOpt 参数接受一个函数。如果提供,所有位于 constructorOpt 之上的堆栈帧(包括 constructorOpt 本身)将在生成的堆栈跟踪中被省略。

【The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.】

constructorOpt 参数对于向用户隐藏错误生成的实现细节非常有用。例如:

【The constructorOpt argument is useful for hiding implementation details of error generation from the user. For instance:】

function MyError() {
  Error.captureStackTrace(this, MyError);
}

// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame, and retain all frames below it.
new MyError().stack;