W3docs

How to Get JavaScript Stack Trace When Throwing an Exception

Read this JavaScript tutorial and learn useful information about the two methods that are used in programming to get 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 <kbd class="highlighted">console.trace()</kbd> 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 <kbd class="highlighted">console.trace()</kbd>.

Javascript console.trace method

javascript— editable

The stack Property

You can create an Error object and return stack attribute:

Javascript create an Error object and return stack attribute

javascript— editable

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.