"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Capture Stack Traces of Custom Exceptions in JavaScript?

How to Capture Stack Traces of Custom Exceptions in JavaScript?

Published on 2024-11-08
Browse:895

How to Capture Stack Traces of Custom Exceptions in JavaScript?

Getting a Strace of Thrown Exceptions

While JavaScript allows for exceptions to be raised, obtaining a stack trace for a custom exception can be challenging. This article explores various methods to retrieve stack traces specifically for user-defined exceptions.

The stack property of an Error object provides a simple solution. By creating a new Error object and accessing its stack property, you can capture a trace:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

This approach generates a stack trace similar to:

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

This format provides the calling function, URL, and successive calling functions.

For modern browsers, a more straightforward method is available:

console.trace(); // (MDN Reference)

This function captures a stack trace and displays it in the console.

An alternative option was proposed in the original thread:

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);
}

This function recursively traverses the call stack and constructs a stack trace string.

By implementing these methods, developers can effectively obtain stack traces for custom JavaScript exceptions, enabling more robust error handling and debugging.

Release Statement This article is reprinted at: 1729175015 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3