首頁 > web前端 > js教程 > 主體

如何檢索自訂 JavaScript 異常的堆疊追蹤?

Linda Hamilton
發布: 2024-10-17 22:28:29
原創
139 人瀏覽過

How to Retrieve Stack Traces for Custom JavaScript Exceptions?

Getting JavaScript Stack Traces for Custom Exceptions

When running your JavaScript code, exceptions can provide valuable insights into issues your script encounters. However, getting stack traces for exceptions you throw yourself poses a challenge. This article addresses this problem and provides solutions to obtain stack traces specifically for your own exceptions.

Initially, it was only possible to get stack traces for built-in JavaScript exceptions. However, advancements in modern browsers have introduced new techniques to address this limitation.

Console.trace() for Modern Browsers

In recent browsers, the console.trace() method is available. By calling it, you can obtain a stack trace that includes the location of the console.trace() invocation.

<code class="javascript">console.trace();</code>
登入後複製

Error Stack Property for All Browsers

A refined solution shared by commenters on the original question involves utilizing the stack property of an Error object.

<code class="javascript">function stackTrace() {
    var err = new Error();
    return err.stack;
}</code>
登入後複製

This approach provides a detailed stack trace similar to the output generated by console.trace():

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
登入後複製

Custom Stack Trace Function

In older browsers that don't support these methods, a more complex function can be used to obtain a custom stack trace:

<code class="javascript">function stacktrace() {
  function st2(f) {
    return !f ? [] :
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}</code>
登入後複製

以上是如何檢索自訂 JavaScript 異常的堆疊追蹤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!