From: David ‘Bombe’ Roden Date: Mon, 26 Feb 2024 19:12:05 +0000 (+0100) Subject: ✨ Add exception suppressor that run code when an exception is caught X-Git-Tag: v2~24 X-Git-Url: https://git.pterodactylus.net/?p=rhynodge.git;a=commitdiff_plain;h=3fc65e842c0c2931b90629851ee986ece69565d6 ✨ Add exception suppressor that run code when an exception is caught --- diff --git a/src/main/kotlin/net/pterodactylus/util/exception/Exceptions.kt b/src/main/kotlin/net/pterodactylus/util/exception/Exceptions.kt new file mode 100644 index 0000000..5302e08 --- /dev/null +++ b/src/main/kotlin/net/pterodactylus/util/exception/Exceptions.kt @@ -0,0 +1,16 @@ +package net.pterodactylus.util.exception + +/** + * Runs the given [runnable][Runnable], catching any [exceptions][Exception], + * and running the [errorRunnable][Runnable] with a caught exception. + * + * @param runnable The block to run + * @param errorRunnable The block to run in case of an exception + */ +fun suppressException(runnable: () -> Unit = {}, errorRunnable: (e: Exception) -> Unit = {}): () -> Unit = { + try { + runnable() + } catch (e: Exception) { + errorRunnable(e) + } +} diff --git a/src/test/kotlin/net/pterodactylus/util/exception/ExceptionsTest.kt b/src/test/kotlin/net/pterodactylus/util/exception/ExceptionsTest.kt new file mode 100644 index 0000000..151da89 --- /dev/null +++ b/src/test/kotlin/net/pterodactylus/util/exception/ExceptionsTest.kt @@ -0,0 +1,31 @@ +package net.pterodactylus.util.exception + +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.junit.Test +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +class ExceptionsTest { + + @Test + fun `runnable is run by suppress method`() { + val runnabledCalled = AtomicBoolean(false) + suppressException({ runnabledCalled.set(true) })() + MatcherAssert.assertThat(runnabledCalled.get(), Matchers.equalTo(true)) + } + + @Test + fun `exception thrown in runnable is suppressed`() { + suppressException({ throw RuntimeException() })() + } + + @Test + fun `error runnable is called with exception`() { + val caughtException = AtomicReference() + suppressException({ throw IllegalStateException("Test") }) { caughtException.set(it) }() + MatcherAssert.assertThat(caughtException.get(), Matchers.instanceOf(RuntimeException::class.java)) + MatcherAssert.assertThat(caughtException.get().message, Matchers.equalTo("Test")) + } + +}