From de7264bd791f36a47fb82d03116f5704ce5a2501 Mon Sep 17 00:00:00 2001 From: Benedikt Waldvogel Date: Tue, 24 Sep 2024 14:53:17 +0200 Subject: [PATCH] Action: Improve catching and rethrowing of RuntimException --- src/main/java/de/cronn/commons/lang/Action.java | 2 ++ .../java/de/cronn/commons/lang/ActionTest.java | 15 +++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/main/java/de/cronn/commons/lang/Action.java b/src/main/java/de/cronn/commons/lang/Action.java index c074fe2..80b689c 100644 --- a/src/main/java/de/cronn/commons/lang/Action.java +++ b/src/main/java/de/cronn/commons/lang/Action.java @@ -15,6 +15,8 @@ default Supplier toSupplier() { return () -> { try { execute(); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { throw new RuntimeException(e); } diff --git a/src/test/java/de/cronn/commons/lang/ActionTest.java b/src/test/java/de/cronn/commons/lang/ActionTest.java index 2a5ca50..e1e27b0 100644 --- a/src/test/java/de/cronn/commons/lang/ActionTest.java +++ b/src/test/java/de/cronn/commons/lang/ActionTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.*; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import org.junit.jupiter.api.Test; @@ -20,6 +21,20 @@ void testToSupplier() { assertThat(numberOfExecutions.get()).isEqualTo(1); } + @Test + void testToSupplier_catchesRuntimeExceptionWithoutWrapping() { + Action action = () -> { + throw new IllegalArgumentException("some test exception"); + }; + + Supplier supplier = action.toSupplier(); + + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(supplier::get) + .withMessage("some test exception") + .withNoCause(); + } + @Test void testToCallable() throws Exception { Action action = numberOfExecutions::incrementAndGet;