From 3fc65e842c0c2931b90629851ee986ece69565d6 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Mon, 26 Feb 2024 20:12:05 +0100 Subject: [PATCH] =?utf8?q?=E2=9C=A8=20Add=20exception=20suppressor=20that?= =?utf8?q?=20run=20code=20when=20an=20exception=20is=20caught?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- .../net/pterodactylus/util/exception/Exceptions.kt | 16 +++++++++++ .../pterodactylus/util/exception/ExceptionsTest.kt | 31 ++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 src/main/kotlin/net/pterodactylus/util/exception/Exceptions.kt create mode 100644 src/test/kotlin/net/pterodactylus/util/exception/ExceptionsTest.kt 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")) + } + +} -- 2.7.4