You could use console.trace()
instead of console.error()
.
This is what you see on the console with console.trace()
:
Trace
func3 @ js:24
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12
And this with console.error()
:
Custom Error
console.error @ snippet-javascript-console.min.js?v=1:1
func3 @ js:23
func2 @ js:19
func1 @ js:15
(anonymous) @ js:12
If you want to get the stack trace into a variable instead of just logging it, you can use Error.captureStackTrace(targetObject)
or Error().stack
, but both are non-standard:
func1();
function func1() {
func2();
}
function func2() {
func3();
}
function func3() {
const fakeErrorObject = {};
Error.captureStackTrace(fakeErrorObject)
const captureStackTraceTrace = fakeErrorObject.stack;
const errorStackTrace = Error('Foo').stack;
console.log(captureStackTraceTrace.replaceAll('at', ''));
console.log(errorStackTrace.replaceAll('at', ''));
}
.as-console-wrapper {
max-height: none !important;
}