Nodejs Error captureStackTrace example| Javascript print stack trace as a string

In Java, We use to print the stack trace with the inbuilt method.

In Nodejs, It provides captureStackTrace method in the Error object to get call stack information. It creates a .stack property with information about a target object.

It provides the user-defined function to capture the stack call trace. You can also check other posts on npm command deprecate option is deprecated Syntax:

captureStackTrace(Object[, constructorFunciton])

Object: It is a target error object which returns the string that contains the line number in the location code with a stack trace. An constructorFunciton: Error custom object

Here is an Nodejs captureStackTrace example

const employee = { "id": 1, "name": "john" };
Error.captureStackTrace(employee);
console.log(employee.stack);

Output:

A:\work\nodework>node error.js
john
at Object.<anonymous> (A:\work\nodework\error.js:2:7)
at Module.\_compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module.\_extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module.\_load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain](internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47

Let’s see another example

Let’s define a function, printed stack property and returns undefined

function MyError() {}

console.log(new MyError().stack);

Output:

undefined

Let’s add a function with the captureStackTrace method with an error object

function MyError() {
  Error.captureStackTrace(this, MyError);
}
console.log(new MyError().stack);

Output:

Error
at Object.<anonymous> (A:\work\nodework\error.js:8:13)
at Module.\_compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module.\_extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module.\_load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain](internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47

It helps users to hide the implementation error details