How to display stack trace on a caught exception?
Solution 1
I use the ExceptionUtils#getFullStackTrace method of Jakarta Commons Lang
Solution 2
Your logging framework should have the ability to log exceptions, so simply passing the exception to the proper .error(Object, Throwable)
call should be enough:
- log4j can do it
- commons logging can do it
-
java.util.logging
can do it
If your logging framework can't do that, or you need the stack trace in a String
for any other reason, then it becomes a bit harder. You'll have to create a PrintWriter
wrapping a StringWriter
and call .printStackTrace()
on the Exception
:
StringWriter sw = new StringWriter();
ex.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
Solution 3
Have you tried?
private void _showErrorMessage(Exception e) {
log.error("Hey! got an exception", e);
}
Solution 4
Throwable.getStackTrace
returns an array of StackTraceElement
s, hence the toString
method is returning a textual representation of the array itself.
In order to actually retrieve the stack trace information, one would have to go through each StackTraceElement
to get more information.
Solution 5
You could also look at the Guava libraries from Google.
Throwables.getStackTraceAsString(Throwable throwable)
Comments
-
ufk over 3 years
I have a generic function that prints exceptions (using log4j):
private void _showErrorMessage(Exception e) { log.error(e.getClass() + ": " + e.getMessage() + ": " + e.getCause() + "\n" + e.getStackTrace().toString()); }
Instead of seeing the stack trace I'm seeing:
[Ljava.lang.StackTraceElement;@49af7e68
How can I view the stack trace of the exception properly?
update
log.error(e) <- shows the error, but doesn't show stack trace