Use a utility method to get a String of a Throwable.

This commit is contained in:
asofold 2014-11-11 20:25:28 +01:00
parent 0201e4178b
commit 780d59d8a7
3 changed files with 35 additions and 7 deletions

View File

@ -165,4 +165,35 @@ public class StringUtil {
return p[n];
}
/**
* Just return the stack trace as new-line-separated string.
* @param t
* @param header Add a header about the exception itself, if set to true.
* @return
*/
public static final String stackTraceToString(final Throwable t, final boolean header) {
// TODO: Consider to use System.getProperty("line.separator").
final StringBuilder b = new StringBuilder(325);
if (header) {
b.append(t.toString()); // TODO: Check.
b.append("\n");
}
final StackTraceElement[] elements = t.getStackTrace();
for (int i = 0; i < elements.length; i++) {
b.append(elements[i]);
b.append("\n");
}
return b.toString();
}
/**
* Convenience method for stackTraceToString(t).
* @param t
* @return
*/
public static final String throwableToString(final Throwable t) {
return stackTraceToString(t, true);
}
}

View File

@ -28,10 +28,7 @@ public class LogUtil {
}
public static String toString(final Throwable t){
// TODO: Find the fastest way.
final StringWriter w = new StringWriter();
t.printStackTrace(new PrintWriter(w));
return w.toString();
return StringUtil.throwableToString(t);
}

View File

@ -11,6 +11,8 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import fr.neatmonster.nocheatplus.utilities.StringUtil;
/**
* Could not think of anything better, likely a refactoring stage.
* @author mc_dev
@ -58,9 +60,7 @@ public class StaticLogFile {
builder.append('\n');
if (ex != null) {
final StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
builder.append(writer);
builder.append(StringUtil.throwableToString(ex));
}
return builder.toString();