How to Get JavaScript Stack Trace When Throwing an Exception

The stack trace method identifies the error of the program when the function of that program is executed. It helps programmers check where the specific exception comes and what is the reason behind it. Here we suggest two simple methods which are supported by all major Web Browsers to get JavaScript stack trace when throwing an exception.

console.trace

You can simply use the console.trace() method of the console object which gives the trace on the console. It will show the call path taken to reach the point at which you call console.trace().

function sum(a, b) {
  //open your browser console to see the result
  console.trace('sum called with ', a, 'and', b);
  return a + b;
}
// Calculation function  
function calc() {
  let s = sum(10, 11) + sum(12, 14);
  return s;
}
// Start function 
function start() {
  let a = sum(1, 3);
  let b = calc();
  console.log(a);
  console.log(b);
}
// Calling start function  
start();

The stack Property

You can create an Error object and return stack attribute:

function stackTrace() {
  let err = new Error();
  console.log(err.stack);
}
stackTrace();

Error objects are thrown when runtime errors appear. It can also be used as a base object for user-defined exceptions. The stack is a non-standard property of Error objects that offers a trace of which functions were invoked, in what order, from which line and file, and with what arguments. Stack string proceeds from the latest calls to the earlier ones, leading back to the original global scope call.


Do you find this helpful?

Related articles