Using Typescript, how do I get just the stacktrace from the error?
For example look at this sample code:
} catch (err: any) {
console.log(err.message);
console.log(err.stackTrace);
console.log(err.stack);
console.log(err);
}
Take a look at these results from the above code:
What method or property do I use to get only the 3 lines of the stacktrace?
1) err.message: provides he error message as expected.
2) err.stackTrace: provides and object but I'm not sure exactly what.
3) err.stack: and "err" return exactly the same thing - everything.
Thank you.
CodePudding user response:
to get the stack trace we can use the stack
property of the Error
instance as documented on MDN Web Docs.
Lets store the result of following operations in a variable called stack
. Lets utilise the new line character in the stack to separate the lines into array elements. After that we can slice()
the array to ignore first index which is the error message and take the next 3 elements to include the 3 lines as required, since we are using slice(1, 4)
we are guaranteed at most 3 lines of the stack trace. After that we can join these array elements into string using join("\n")
to join with new line character.
The code goes as the following:
const stack = err.stack.split("\n").slice(1, 4).join("\n");
console.log(stack); // to view the result