Maison  >  Article  >  interface Web  >  Comment récupérer les traces de pile pour les exceptions JavaScript personnalisées ?

Comment récupérer les traces de pile pour les exceptions JavaScript personnalisées ?

Linda Hamilton
Linda Hamiltonoriginal
2024-10-17 22:28:29140parcourir

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>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn