private static <X extends Throwable> void runOnFailure(Runnable action, Class<? extends X> type, java.util.function.Consumer<X> consumer) { try { action.tryRun(); } catch (Throwable x) { if (type.isInstance(x)) { consumer.accept(type.cast(x)); } throw sneakyThrow(x); } }
private static <X extends Throwable> void runUnwrap(Runnable action, Class<? extends X> type) { try { action.tryRun(); } catch (Throwable x) { if (isFatal(x)) { throw sneakyThrow(x); } Throwable t = x; if (type.isInstance(x)) { t = Optional.ofNullable(x.getCause()).orElse(x); } throw sneakyThrow(t); } }
private static void runWrap(Runnable action, java.util.function.Function<Throwable, Exception> wrapper) { try { action.tryRun(); } catch (Throwable x) { if (isFatal(x)) { throw sneakyThrow(x); } throw sneakyThrow(wrapper.apply(x)); } }
/** * Unwrap an exception and rethrow. Useful to produce clean/shorter stacktraces. * * @param type Type to unwrap. * @param <X> Exception type. * @return A new consumer. */ default <X extends Throwable> Runnable unwrap(Class<? extends X> type) { return () -> runUnwrap(() -> tryRun(), type); } }
/** * Wrap an exception as new exception provided by the given wrap function. * * @param wrapper Wrap function. * @return A new consumer. */ default Runnable wrap(java.util.function.Function<Throwable, Exception> wrapper) { return () -> runWrap(() -> tryRun(), wrapper); }
private static void runAction(Runnable action) { try { action.tryRun(); } catch (Throwable x) { throw sneakyThrow(x); } }
/** * Execute the given action before throwing the exception. * * @param type Exception type filter. * @param action Action to execute. * @param <X> Exception type. * @return A new consumer with a listener action. */ default <X extends Throwable> Runnable onFailure(Class<? extends X> type, java.util.function.Consumer<X> action) { return () -> runOnFailure(() -> tryRun(), type, action); }