Rumah  >  Artikel  >  hujung hadapan web  >  Bagaimana untuk Mendapatkan Jejak Tindanan untuk Pengecualian JavaScript Tersuai?

Bagaimana untuk Mendapatkan Jejak Tindanan untuk Pengecualian JavaScript Tersuai?

Linda Hamilton
Linda Hamiltonasal
2024-10-17 22:28:29140semak imbas

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>

Atas ialah kandungan terperinci Bagaimana untuk Mendapatkan Jejak Tindanan untuk Pengecualian JavaScript Tersuai?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn