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.
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