Last active
April 6, 2019 18:09
-
-
Save progulin/6871c1502c807b49a3dd2274cb29949d to your computer and use it in GitHub Desktop.
It wraps throwable chain to unchecked Exception, which can be accepted by any client.Usefull for IPC.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static final String MESSAGE_DELIMITER = System.lineSeparator() + "-> "; | |
public static RuntimeException wrapToRuntimeException(Throwable t) { | |
return wrapTo(RuntimeException.class, t); | |
} | |
public static <C extends Class<? extends RuntimeException>> RuntimeException wrapTo(C clazz, Throwable t) { | |
return wrapTo(clazz, t, Main::chainCauseMessages); | |
} | |
public static <C extends Class<? extends RuntimeException>> RuntimeException wrapTo(C clazz, Throwable t, Function<Throwable, String> messageCreator) { | |
return setStackTraceSafely(createWrapperSafely(clazz, createMessageSafely(t, messageCreator)), t); | |
} | |
public static String chainCauseMessages(Throwable t) { | |
return chainCauseMessages(t, MESSAGE_DELIMITER); | |
} | |
public static String chainCauseMessages(Throwable t, String delimiter) { | |
StringJoiner sj = new StringJoiner(delimiter); | |
Lists.reverse(ExceptionUtils.getThrowableList(t)).stream().map(Object::toString).forEach(sj::add); | |
return sj.toString(); | |
} | |
private static String createMessageSafely(Throwable t, Function<Throwable, String> messageCreator) { | |
try { | |
return messageCreator.apply(t); | |
} catch (Exception ignored) { | |
return ExceptionUtils.getRootCauseMessage(t); | |
} | |
} | |
@NotNull | |
private static <C extends Class<? extends RuntimeException>> RuntimeException createWrapperSafely(C clazz, String message) { | |
try { | |
return clazz.getDeclaredConstructor(String.class).newInstance(message); | |
} catch (Exception ignored) { | |
try { | |
return clazz.getDeclaredConstructor(String.class, Throwable.class).newInstance(message, null); | |
} catch (Exception ignored2) { | |
return new RuntimeException(message); | |
} | |
} | |
} | |
private static RuntimeException setStackTraceSafely(RuntimeException wrapped, Throwable t) { | |
try { | |
wrapped.setStackTrace(ExceptionUtils.getRootCause(t).getStackTrace()); | |
} catch (Exception ignored) { | |
} | |
return wrapped; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment