Error.captureStackTrace(targetObject[, constructorOpt])
-
targetObject<Object> -
constructorOpt<Function>
在 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;