Last active
September 21, 2016 12:45
-
-
Save ovstetun/e84bc62b52abed933646 to your computer and use it in GitHub Desktop.
exceptionwrapping
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
Runtime.getRuntime().addShutdownHook(new Thread(() -> consumer(server::close))); | |
File tempFile = propagate(() -> File.createTempFile("util-tests", ".tmp")); |
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 class Java8Util { | |
public static interface ExceptionWrapper<E> { | |
E wrap(Exception e); | |
} | |
public static <T> T propagate(Callable<T> callable) throws RuntimeException { | |
return propagate(callable, RuntimeException::new); | |
} | |
public static <T, E extends Throwable> T propagate(Callable<T> callable, ExceptionWrapper<E> wrapper) throws E { | |
try { | |
return callable.call(); | |
} catch (RuntimeException e) { | |
throw e; | |
} catch (Exception e) { | |
throw wrapper.wrap(e); | |
} | |
} | |
public interface RunnableWithException { | |
public void run() throws Exception; | |
} | |
public static void consumer(RunnableWithException runnable) throws RuntimeException { | |
consumer(runnable, RuntimeException::new); | |
} | |
public static void consumer(RunnableWithException runnable, ExceptionWrapper<RuntimeException> wrapper) { | |
try { | |
runnable.run(); | |
} catch (RuntimeException e) { | |
throw e; | |
} catch (Exception e) { | |
throw wrapper.wrap(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment