Error.captureStackTrace(targetObject[, constructorOpt])


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

const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack;  // 类似于`new Error().stack`

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

可选的 constructorOpt 参数接受一个函数。 如果给定,则所有 constructorOpt 以上的帧,包括 constructorOpt,都将从生成的堆栈跟踪中省略。

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

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

// 如果不将 MyError 传给 captureStackTrace,
// 则 MyError 帧将显示在 .stack 属性中。
// 通过传入构造函数,则省略该帧,并保留其下方的所有帧。
new MyError().stack;

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`

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

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

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;