CheckFunctionUtils { public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function, CheckedFunction1<Throwable, T> exceptionHandler) { return () -> { try { return function.apply(); } catch (Throwable throwable) { return exceptionHandler.apply(throwable); } }; } private  CheckFunctionUtils(); static CheckedFunction0<T> recover(CheckedFunction0<T> function,
        CheckedFunction1<Throwable, T> exceptionHandler); static CheckedFunction0<R> andThen(CheckedFunction0<T> function,
        CheckedFunction2<T, Throwable, R> handler); static CheckedFunction0<T> recover(CheckedFunction0<T> function,
        Predicate<T> resultPredicate, CheckedFunction1<T, T> resultHandler); static CheckedFunction0<T> recover(CheckedFunction0<T> function,
        List<Class<? extends Throwable>> exceptionTypes,
        CheckedFunction1<Throwable, T> exceptionHandler); static CheckedFunction0<T> recover(CheckedFunction0<T> function,
        Class<X> exceptionType,
        CheckedFunction1<Throwable, T> exceptionHandler);  }
@Test public void shouldRecoverFromException() throws Throwable { CheckedFunction0<String> callable = () -> { throw new IOException("BAM!"); }; CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, (ex) -> "Bla"); String result = callableWithRecovery.apply(); assertThat(result).isEqualTo("Bla"); }
@Test public void shouldRecoverFromSpecificExceptions() throws Throwable { CheckedFunction0<String> callable = () -> { throw new IOException("BAM!"); }; CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, asList(IllegalArgumentException.class, IOException.class), (ex) -> "Bla"); String result = callableWithRecovery.apply(); assertThat(result).isEqualTo("Bla"); }
@Test public void shouldRecoverFromSpecificResult() throws Throwable { CheckedFunction0<String> supplier = () -> "Wrong Result"; CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(supplier, (result) -> result.equals("Wrong Result"), (r) -> "Bla"); String result = callableWithRecovery.apply(); assertThat(result).isEqualTo("Bla"); }
@Test(expected = RuntimeException.class) public void shouldRethrowException() throws Throwable { CheckedFunction0<String> callable = () -> { throw new IOException("BAM!"); }; CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, (ex) -> { throw new RuntimeException(); }); callableWithRecovery.apply(); }
@Test(expected = RuntimeException.class) public void shouldRethrowException2() throws Throwable { CheckedFunction0<String> callable = () -> { throw new RuntimeException("BAM!"); }; CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, IllegalArgumentException.class, (ex) -> "Bla"); callableWithRecovery.apply(); }