迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

从 JavaScript 的错误中获取堆栈跟踪

作者:迹忆客 最近更新:2022/11/22 浏览次数:

使用 console.trace() 方法从错误中获取堆栈跟踪。 console.trace() 方法输出堆栈跟踪并显示到达调用该方法的点所采用的调用路径。

function outer() {
  function inner() {
    console.trace();
  }

  inner();
}

outer();

我们定义了一个嵌套函数,我们在其中调用了 console.trace() 方法并调用了外部函数。

如果我们在浏览器中,该方法会将堆栈跟踪输出到控制台;如果在 Node.js 中,则该方法会将堆栈跟踪输出到终端。

JavaScript 的错误中获取堆栈跟踪

该消息显示了到达我们调用 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 对象上的堆栈属性是非标准的,不在标准轨道上。

这是将堆栈属性记录到控制台的输出。

JavaScript 的错误中获取堆栈跟踪 error stack

Error 对象的堆栈属性显示调用了哪些函数、以何种顺序、在哪个文件中以及在哪一行。

没有标准格式,因此消息在不同浏览器之间看起来会有所不同。

消息中的行号表示:

  • Error 对象的堆栈属性记录在 index.js 文件的第 10 行。
  • 错误对象是在第 9 行的内部函数中创建的。
  • index.js 文件的第 13 行,外部函数调用了内部函数。
  • index.js 文件的全局范围内的第 16 行调用了外部函数。

选择哪种方法是个人喜好的问题。 我会使用 console.trace() 方法,因为它在浏览器之间是标准化的。 如果我们使用 stack 属性,结果可能因浏览器而异,并且某些浏览器可能会放弃对它的支持或不实现它,因为它是一个非标准属性。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便