从 JavaScript 的错误中获取堆栈跟踪
使用 console.trace()
方法从错误中获取堆栈跟踪。 console.trace()
方法输出堆栈跟踪并显示到达调用该方法的点所采用的调用路径。
function outer() {
function inner() {
console.trace();
}
inner();
}
outer();
我们定义了一个嵌套函数,我们在其中调用了 console.trace()
方法并调用了外部函数。
如果我们在浏览器中,该方法会将堆栈跟踪输出到控制台;如果在 Node.js 中,则该方法会将堆栈跟踪输出到终端。
该消息显示了到达我们调用 console.trace()
方法的点所经过的路径。
示例中的堆栈跟踪显示内部函数是从外部函数调用的,外部函数是从全局范围调用的。
该消息还显示定义函数的文件的名称。
消息中的行号表示:
- 在第 9 行的 index.js 文件中调用了 console.trace 方法。
- 内部函数在第 9 行调用了 console.trace 方法。
- 外部函数在第 12 行的 index.js 文件中称为内部函数。
- 在第 15 行的 index.js 文件的全局范围内调用了外部函数。
另一种方法是使用 Error.stack
属性从错误中获取堆栈跟踪。
function outer() {
function inner() {
const err = new Error('Something went wrong');
console.log(err.stack);
}
inner();
}
outer();
应该注意的是,Error 对象上的堆栈属性是非标准的,不在标准轨道上。
这是将堆栈属性记录到控制台的输出。
Error
对象的堆栈属性显示调用了哪些函数、以何种顺序、在哪个文件中以及在哪一行。
没有标准格式,因此消息在不同浏览器之间看起来会有所不同。
消息中的行号表示:
-
Error
对象的堆栈属性记录在 index.js 文件的第 10 行。 - 错误对象是在第 9 行的内部函数中创建的。
- 在 index.js 文件的第 13 行,外部函数调用了内部函数。
- 在 index.js 文件的全局范围内的第 16 行调用了外部函数。
选择哪种方法是个人喜好的问题。 我会使用
console.trace()
方法,因为它在浏览器之间是标准化的。 如果我们使用 stack 属性,结果可能因浏览器而异,并且某些浏览器可能会放弃对它的支持或不实现它,因为它是一个非标准属性。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。