What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
if you are using java 8, try this
you can find the code for getStackTrace() function provided by Throwable.java as :
and for StackTraceElement, it providers toString as:
So just join the StackTraceElement with "\n"
Here is a version that is copy-pastable directly into code:
Or, in a catch block
The clever sniping in the first set of comments was very amusing, but it really depends on what you are trying to do. If you don't already have the correct library, then 3 lines of code (as in D. Wroblewski's answer) is perfect. OTOH, if you already have the apache.commons library (as most large projects will), then Amar's answer is shorter. OK, it might take you ten minutes to get the library and install it correctly (less than one if you know what you're doing). But the clock is ticking, so you may not have the time to spare. Jarek Przygódzki had an interesting caveat--"If you don't need nested exceptions".
But what if I do need the full stack traces, nested and all? In that case, the secret is to use apache.common's getFullStackTrace (see http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/exception/ExceptionUtils.html#getFullStackTrace%28java.lang.Throwable%29)
It saved my bacon. Thanks, Amar, for the hint!
Old question, but I would just like to add the special case where you don't want to print all the stack, by removing some parts you are not actually interested in, excluding certain classes or packages.
Instead of a
PrintWriter
use aSelectivePrintWriter
:Where the
SelectivePrintWriter
class is given by:Please note this class may be easily adapted to filter out by Regex,
contains
or other criteria. Also note it depends uponThrowable
implementation details (not likely to change, but still).My oneliner to convert stack trace to the enclosed multi-line string:
Easy to pass to the logger "as is".
Few options
StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String exceptionAsString = sw.toString();
Using Google Guava lib
String stackTrace = Throwables.getStackTraceAsString ( myException ) ;
org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(Throwable)