How to get JavaScript stack trace when throw an exception ?
Last Updated :
25 Jun, 2024
A stack trace is a crucial tool for identifying errors in a program when a function is called. It allows programmers to pinpoint where an error or exception occurred and understand its cause. Stack traces report the active stack frames at a specific moment during execution, showing the memory allocated dynamically in the stack. This method is commonly used in debugging to trace errors and helps programmers diagnose issues effectively.
Stack
In this data structure where data can be stored in the form of last in first out (LIFO). It means the stack is a type of storage and when a group of data comes inside the stack, it stores them one by one in such a removed manner where the last data is removed first and the first data is removed last. The way any group of data is stored the and removed from the stack can be understood by stack trace.
There are several methods by which we can get a stack trace for JavaScript when throwing an exception. which are as follows:
Using console.trace
The console object also has a method called console.trace() method, which gives you the trace on the console. Every time when it is called stack trace generate for the function. We can understand this with the help of this example.
JavaScript
// Sum function
function sum(a, b) {
console.trace('sum called with ', a, 'and', b);
return a + b;
}
// Calculation function
function calc() {
return sum(8, 11) + sum(9, 14);
}
// Start function
function start() {
var a = sum(2, 3);
var b = calc();
}
// Calling start function
start();
Output:
/usr/bin/node stacktrace.js
Trace: add called with 2 and 3
at sum (/home/dev/Documents/stacktrace.js:2:13)
at start (/home/dev/Documents/stacktrace.js:11:13)
at Object. (/home/dev/Documents/stacktrace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Trace: add called with 8 and 11
at sum (/home/dev/Documents/stacktrace.js:2:13)
at calc (/home/dev/Documents/stacktrace.js:7:12)
at start (/home/dev/Documents/stacktrace.js:12:13)
at Object. (/home/dev/Documents/stacktrace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Trace: add called with 9 and 14
at sum (/home/dev/Documents/stacktrace.js:2:13)
at calc (/home/dev/Documents/stacktrace.js:7:25)
at start (/home/dev/Documents/stacktrace.js:12:13)
at Object. (/home/dev/Documents/stacktrace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Using Error Object
We can create an Error object and return stack attribute. A non-standard stack property of Error object gives you the stack trace when that particular function was called from which line and file, and with what arguments. The stack string proceeds from the most recent calls to earlier ones.
Example: To demonstrate the getting JavaScript Stack tree when throwing an exception using error object.
JavaScript
// Sum function
function sum(a, b) {
console.log(new Error().stack);
return a + b;
}
// Calculation function
function calc() {
return sum(8, 11) + sum(9, 14);
}
// Start function
function start() {
var a = sum(2, 3);
var b = calc();
}
// Calling start function
start();
Output:
/usr/bin/node trace.js
Error
at sum (/home/dev/Documents/trace.js:2:17)
at start (/home/dev/Documents/trace.js:11:13)
at Object. (/home/dev/Documents/trace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Error
at sum (/home/dev/Documents/trace.js:2:17)
at calc (/home/dev/Documents/trace.js:7:12)
at start (/home/dev/Documents/trace.js:12:13)
at Object. (/home/dev/Documents/trace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Error
at sum (/home/dev/Documents/trace.js:2:17)
at calc (/home/dev/Documents/trace.js:7:25)
at start (/home/dev/Documents/trace.js:12:13)
at Object. (/home/dev/Documents/trace.js:16:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
at internal/main/run_main_module.js:17:11
Using caller object
We implemented a stacktrace function that returns the call history as a string up to the point it was called. It uses a recursive st2 function, called with arguments.callee.caller, to traverse the call-tree and build the stacktrace string.
Example: To demonstrate the getting JavaScript Stack tree when throwing an exception using caller object.
JavaScript
// Sum function
function sum(a,b) {
// Calling stacktrace function
console.log(stacktrace());
return a+b;
}
// Calculation function
function calc() {
return sum(8, 11) + sum(9, 14);
}
// Start function
function start() {
var a = sum(2, 3);
var b = calc();
}
// Calling start function
start();
// Stacktrace function
function stacktrace() {
function st2(f) {
var args = [];
if (f) {
for (var i = 0; i < f.arguments.length; i++) {
args.push(f.arguments[i]);
}
var function_name = f.toString().
split('(')[0].substring(9);
return st2(f.caller) + function_name +
'(' + args.join(', ') + ')' + "\n";
} else {
return "";
}
}
return st2(arguments.callee.caller);
}
Output:
/usr/bin/node stackt.js
([object Object], function require(path) {
return mod.require(path);
}, [object Object], /home/dev/Documents/stackt.js, /home/dev/Documents)
start()
sum(2, 3)
([object Object], function require(path) {
return mod.require(path);
}, [object Object], /home/dev/Documents/stackt.js, /home/dev/Documents)
start()
calc()
sum(8, 11)
([object Object], function require(path) {
return mod.require(path);
}, [object Object], /home/dev/Documents/stackt.js, /home/dev/Documents)
start()
calc()
sum(9, 14)
Similar Reads
How to rethrow an exception in JavaScript, but preserve the stack?
Stack trace conveys some portion of the data whenever an exception is thrown. The stack trace is a collection of all the methods used in the program. It starts with the method that throws an exception and ends with the method that catches the exception. In case if an exception is re-thrown, the stac
3 min read
JavaScript Errors Throw and Try to Catch
JavaScript uses throw to create custom errors and try...catch to handle them, preventing the program from crashing. The finally block ensures that code runs after error handling, regardless of success or failure.throw: Used to create custom errors and stop code execution.try...catch: Allows you to c
3 min read
Which Keywords are used to handle Exceptions in JavaScript ?
JavaScript handles exceptions through the âtry..catch...finallyâ statement. An example statement is shown below. javascript try { // Attempt to execute this code } catch (exception) { // This code handles exceptions } finally { // This code always gets executed } The first element of a âtry...catch.
4 min read
What is the Call Stack in JavaScript ?
In JavaScript, the Call Stack is an essential concept that helps the JavaScript engine keep track of function execution. It plays a vital role in managing the execution order of functions and determining how the JavaScript program handles function calls.How Does the Call Stack Work?JavaScript operat
4 min read
How to throw an error in an async generator function in JavaScript ?
In this article, we will try to understand how to throw an error in a synchronous (abbreviated as "async") generator function in JavaScript with the help of theoretical as well as coding examples. Let us first have a look into the following section which will show us the syntax for declaring an asyn
2 min read
How to Print a Message to the Error Console Using JavaScript ?
This article will show you how to print a message using JavaScript on the error console. There are three methods to display the error console, these are: Table of Content Using console.error() MethodUsing console.warn() MethodUsing console.info() MethodApproach 1: Using console.error() MethodThe con
2 min read
Testing the Type of a Thrown Exception in Jest
Testing is a crucial aspect of software development, ensuring that code behaves as expected under various conditions. Jest, a popular JavaScript testing framework, provides powerful tools for testing different scenarios, including handling and testing exceptions. Whenever a function or method is sup
4 min read
How to find out the caller function in JavaScript?
In this article, we see the methods to find out the caller function in Javascript. Sometimes, the developer may want to modify how a function works on the basis of its caller function. To find out the caller function name, we will use the Function object's caller property. Property: Function.caller
1 min read
JavaScript - throw not working in an error handling situation
In this article, we will try to understand in which case or how does throw statement doesn't work in an error handling situation and how does or by which way possible we may correct it in order to produce the correct output with the help of certain examples in JavaScript. Let us have a look over the
3 min read
Javascript AsyncGenerator.prototype.throw() Method
JavaScript AsyncGenerator.prototype.throw() method is used with asynchronous generators to throw an exception into the generator and handle it within the generator function. It returns a Promise that resolves to an object with two properties: value and done. Syntax:AsyncGenerator.prototype.throw(exc
2 min read