>  기사  >  웹 프론트엔드  >  사용자 정의 JavaScript 예외에 대한 스택 추적을 검색하는 방법은 무엇입니까?

사용자 정의 JavaScript 예외에 대한 스택 추적을 검색하는 방법은 무엇입니까?

Linda Hamilton
Linda Hamilton원래의
2024-10-17 22:28:29141검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.