Home  >  Article  >  Web Front-end  >  How Can JavaScript Stack Traces Be Obtained for Custom Exceptions?

How Can JavaScript Stack Traces Be Obtained for Custom Exceptions?

DDD
DDDOriginal
2024-10-17 22:30:03935browse

How Can JavaScript Stack Traces Be Obtained for Custom Exceptions?

How to Obtain a JavaScript Stack Trace for Custom Exceptions

When throwing custom JavaScript exceptions (e.g., throw "AArrggg"), accessing a stack trace (via Firebug or other tools) may only reveal the exception message. This article presents solutions for obtaining full stack traces, even for custom exceptions.

Modern Browser Solution:

In modern browsers, you can conveniently access the stack trace with console.trace().

Error Stack Property:

For a cleaner and simpler solution, you can utilize the stack property of an Error object:

<code class="js">function stackTrace() {
    var err = new Error();
    return err.stack;
}</code>

This approach provides a detailed stack trace, including the calling functions, file paths, and line numbers.

Custom Stack Trace Function:

For more tailored stack trace functionality, consider using the following script:

<code class="js">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>

The above is the detailed content of How Can JavaScript Stack Traces Be Obtained for Custom Exceptions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn