Home > Web Front-end > JS Tutorial > body text

How Can JavaScript Stack Traces Be Obtained for Custom Exceptions?

DDD
Release: 2024-10-17 22:30:03
Original
1002 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!