[main] StringFormatter: support formatting throwables

This commit is contained in:
Johannes Frohnmeyer 2022-09-14 18:04:34 +02:00
parent cc3070420a
commit 09073bb710
Signed by: Johannes
GPG Key ID: E76429612C2929F4
2 changed files with 17 additions and 12 deletions

View File

@ -1,5 +1,6 @@
package io.gitlab.jfronny.commons;
import java.io.*;
import java.util.*;
public class StringFormatter {
@ -10,6 +11,21 @@ public class StringFormatter {
return String.format(Locale.US, "%s", d);
else
return String.format(Locale.US, "%.0f", d);
} else if (o instanceof Throwable t) {
try {
return t.getMessage() + getStackTrace(t);
} catch (IOException e) {
return t.toString();
}
} else return o.toString();
}
public static String getStackTrace(Throwable t) throws IOException {
try (ByteArrayOutputStream baot = new ByteArrayOutputStream()) {
try (PrintStream ps = new PrintStream(baot, true)) {
t.printStackTrace(ps);
}
return baot.toString();
}
}
}

View File

@ -100,17 +100,6 @@ public interface Logger {
default String format(String msg, Throwable t) {
if (t == null) return msg;
return msg + System.lineSeparator() + format(t);
}
default String format(Throwable t) {
try (ByteArrayOutputStream baot = new ByteArrayOutputStream()) {
try (PrintStream ps = new PrintStream(baot, true)) {
t.printStackTrace(ps);
}
return baot.toString();
} catch (IOException e) {
return t.toString();
}
return msg + System.lineSeparator() + StringFormatter.toString(t);
}
}