If you throw
in JavaScript, the thrown error will usually propagate to the window.onerror
handler which can stop the further execution of a script.
Is there any way to get a stack trace from within a function without causing this halting of execution?
You can easily see the stack trace in JavaScript by adding the following into your code: console. trace(); And you'll get an outputted stack trace.
Stacks JavaScript is currently included within various Stack Overflow projects automatically. If you're working on a Stack Overflow project, chances are it's already available for you!
A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.
You can also just create a new error without throwing it and use the stack trace
function doSomething() {
...
const stackTrace = new Error().stack
...
}
Throwing an error will halt the stack unless caught by a try/catch.
function getStack() {
try {
throw new Error();
} catch(e) {
return e.stack;
}
}
Invoking getStack from within any function will print out the stack from there.
Note, the method names in the stack are not affected by sourcemaps, so if you're dealing with minified code you might still get obfuscated names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With