Issue
I want to trace a Java flow whenever there is a Exception happening . I mean Like Consider
Method1 -> Method2 -> Method3 -> Method4 -> Error Came in Method 4 while processing argument1, let’s say we find it invalid.
Then, we could have a response element which looks like below:
“DebugInfo” : “Method1|Method2|Method3|Method4 - Error Came in Method 4 while processing argument1. It is invalid because destination does not support HAL”
Solution
This is exactly what happens using the method getStackTrace:
Provides programmatic access to the stack trace information printed by printStackTrace(). Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.
Note that the order is exactly the opposite as you need (see the bold part)
So you can do something like
StackTraceElement[] elements = exception.getStackTrace();
for (int i = elements.length() - 1; i >= 0; i--) {
System.out.println(elements[i].getMethodName());
}
You need only to add some templating to that to get exactly what you need.
Note that printing (or exporting) only the method name is not enough because generally you have a stack moving through different classes so it is better to print class name and method name. But for larger methods is useful also to know at which row it happened, so... why don't use a simple exception.printStackTrace()
that does exactly what you need?
Answered By - Davide Lorenzo MARINO
Answer Checked By - Marilyn (JavaFixing Volunteer)