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 a() {
b();
}
function b() {
c();
}
function c() {
// Create an error without stack trace to avoid calculating the stack trace twice.
const { stackTraceLimit } = Error;
Error.stackTraceLimit = 0;
const error = new Error();
Error.stackTraceLimit = stackTraceLimit;
// Capture the stack trace above function b
Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
throw error;
}
a();