DEV Community

Cover image for Increase stack trace size by modifying stackTraceLimit property
Sahil Gandhi
Sahil Gandhi

Posted on

Increase stack trace size by modifying stackTraceLimit property

When we get an error while debugging Javascript, we usually check stack trace in the console window of a browser. The default limit of stackTrace is 10 lines. Our applications are usually very complex and we need more than 10 lines of stack trace. This can be done by using property stackTraceLimit of class Error.

In below example is the default stack trace limit which is 10.

function testStackTraceLimit() {
  const hi = () => my();
  const my = () => name();
  const name = () => is();
  const is = () => sahil();
  const sahil = () => {
    throw new Error();
  };
  hi();
}

testStackTraceLimit();
Enter fullscreen mode Exit fullscreen mode

Alt Text

As you can see we have 10 lines of stack Trace.

The limit can be set between 0 and Infinity, negative or non numeric values are converted to 0. 
So if the limit is set to 0, no stack trace is shown and if it is set to infinity, all the stack trace is shown.

function testStackTraceLimit() {
  const hi = () => my();
  const my = () => name();
  const name = () => is();
  const is = () => sahil();
  const sahil = () => {
    throw new Error();
  };
  // hi();
  Error.stackTraceLimit = Infinity;
  console.log("Error stack trace limit: ", Error.stackTraceLimit);
  hi();
}
testStackTraceLimit();
Enter fullscreen mode Exit fullscreen mode

Alt Text

Sometimes we need to reduce the noise of errors, there we can set smaller numeric value. In the next example I will change the limit to 3.

function testStackTraceLimit() {
  const hi = () => my();
  const my = () => name();
  const name = () => is();
  const is = () => sahil();
  const sahil = () => {
    throw new Error();
  };
  // hi();
  Error.stackTraceLimit = 3; 
  console.log("Error stack trace limit: ", Error.stackTraceLimit);
  hi();
}

testStackTraceLimit();
Enter fullscreen mode Exit fullscreen mode

Alt Text

Happy Coding!

Top comments (0)