Configure the logged JavaScript error stack trace length in certain environments
- Published at
- Updated at
- Reading time
- 2min
Debugging JavaScript apps is tough. Today I read an article about debugging functional JavaScript and found a handy language detail.
Let's assume an error is thrown deep inside your app.
main();
function main() {
one();
}
function one() {
two();
}
function two() {
three();
}
// you get the idea :)
function ten () {
eleven()
}
function eleven () {
throw new Error("I can't see the whole stack strace")
}
When you execute this in Chrome or Node.js you get the following stack trace printed to the console.
Uncaught Error: I can't see the whole stack strace
at eleven (<anonymous>:49:9)
at ten (<anonymous>:45:3)
at nine (<anonymous>:41:3)
at eight (<anonymous>:37:3)
at seven (<anonymous>:33:3)
at six (<anonymous>:29:3)
at five (<anonymous>:25:3)
at four (<anonymous>:21:3)
at three (<anonymous>:17:3)
at two (<anonymous>:13:3)
As you see, the first two function calls (main and one) of the stack trace are omitted. It turns out that you can configure the length of the printed stack trace using Error. This configuration enables you to enrich the logging when you're facing a bug buried deep in your application.
Error.stackTraceLimit = 20;
When you increase this value, you will see the whole trace logged.
Uncaught Error: I can't see the whole stack strace
at eleven (<anonymous>:50:9)
at ten (<anonymous>:46:3)
at nine (<anonymous>:42:3)
at eight (<anonymous>:38:3)
at seven (<anonymous>:34:3)
at six (<anonymous>:30:3)
at five (<anonymous>:26:3)
at four (<anonymous>:22:3)
at three (<anonymous>:18:3)
at two (<anonymous>:14:3)
at one (<anonymous>:10:3)
at main (<anonymous>:6:3)
at <anonymous>:2:1
If you use Error you have to be aware of the fact that it is a non-standard according to MDN and a quick check reveals that is also not supported in Firefox. I didn't check Edge.
Also, Chrome and Safari support it but use different default values. Chrome goes with 10 and Safari with 100. When you look around you'll also see that CodeSandbox increases the limit to 50.
In my opinion, this configuration is nothing ground-breaking, but it might become handy someday when I'll debug a large JS app in the browser or a Node.js application. It won't replace the debugger, though...
Join 6.2k readers and learn something new every week with Web Weekly.
