In Java, We use to print the stack tracce with inbuilt method.
In Nodejs, It provides captureStackTrace
method in Error object to get call stack information. It creates .stack
property with information to an target object.
It provides user defined function to capture the stack call trace.
Syntax:
captureStackTrace(Object[, constructorFunciton])
Object
: It is an target error object which returns string that contains line number in location code with 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 an another example
Let’s define function, printed stack
property and returns undefined
function MyError() {
}
console.log(new MyError().stack);
Output:
undefined
Let’s add function with 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