使用本机或未知堆栈帧位置创建错误

Create an error with native or unknown stack frame location

根据 V8 Stack Trace API,本地或未知位置存在错误。香草 js 是否可能产生这些错误?

这是一个很长的话题,但是 v8 是用 c++ 编写的,堆栈是用 c++ 维护的,并在 c++ 抛出新错误时提供给 javascript。但您可以按如下方式发送您自己的自定义错误:

1:捕获错误堆栈:

要获取错误堆栈,您可以通过访问其 .stack 属性.

来访问它

例如:

fs.readFile('./Index.html', function read(err, data) {
    if (err) {
        console.log(err.stack);
    }
});

2:发送您自己的自定义堆栈(基本上是任何文本)

堆栈 属性 像任何 属性 一样添加到对象上,这使您可以执行以下操作:

function trace() {
  try {
    var err = new Error('myError');
    err.stack = "custom written stack!";
    throw err;
  }
  catch(e) {
    console.log(e.stack);
  }
}

3:使用 captureStackTrace 记录正确的自定义堆栈

Error.captureStackTrace(targetObject[, constructorOpt])

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

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 all frames above it.
new MyError().stack

正在捕获一堆抛出的新错误

要捕获新抛出错误的堆栈,您可以编写以下内容:

function trace() {
  try {
    throw new Error('myError');
  }
  catch(e) {
    alert(e.stack);
  }
}
function b() {
  trace();
}

调用 b 将记录以下内容:

Error: myError
    at trace (<anonymous>:3:15)
    at b (<anonymous>:10:7)
    at <anonymous>:1:1

你可能会在 native 使用 Vanilla JS 时遇到错误,如下所示:

> try { String.fromCodePoint(-42); } catch(e) { console.log(e.stack);}
RangeError: Invalid code point -42
    at Function.fromCodePoint (native)
    at <anonymous>:1:14

在V8中,部分功能是用JS实现的。例如,String.fromCodePoint 在这里 https://github.com/v8/v8/blob/5.2-lkgr/src/js/string.js#L784. Other functions are implemented in C++. I believe, if the error is thrown in a JS function, it's native. If the function is implemented in C++, the error is not at native. Here's an error from encodeURI, which is implemented in C++ (https://github.com/v8/v8/blob/master/src/uri.cc#L180).

> try { encodeURI('\uDFFF'); } catch(e) { console.log(e.stack);}
URIError: URI malformed
    at <anonymous>:1:7