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!