From 1b42f65d9534f0ba289070f76fdba4c775c7b850 Mon Sep 17 00:00:00 2001 From: Sculas Date: Tue, 2 Aug 2022 22:16:37 +0200 Subject: [PATCH] refactor: migrate to custom exceptions for patch options --- .../app/revanced/patcher/patch/PatchOption.kt | 16 ++++++++++------ .../revanced/patcher/patch/PatchOptionsTest.kt | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt b/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt index 728d587..2d47507 100644 --- a/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt +++ b/src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt @@ -1,13 +1,16 @@ +@file:Suppress("CanBeParameter", "MemberVisibilityCanBePrivate") + package app.revanced.patcher.patch -@Suppress("CanBeParameter", "MemberVisibilityCanBePrivate") class NoSuchOptionException(val option: String) : Exception("No such option: $option") +class IllegalValueException(val value: Any?) : Exception("Illegal value: $value") +class InvalidTypeException(val got: String, val expected: String) : + Exception("Invalid option value type: $got, expected $expected") /** * A registry for an array of [PatchOption]s. * @param options An array of [PatchOption]s. */ -@Suppress("MemberVisibilityCanBePrivate") class PatchOptions(vararg val options: PatchOption<*>) : Iterable> { private val register = buildMap { for (option in options) { @@ -31,9 +34,10 @@ class PatchOptions(vararg val options: PatchOption<*>) : Iterable * Please note that using the wrong value type results in a runtime error. */ inline operator fun set(key: String, value: T) { - @Suppress("UNCHECKED_CAST") val opt = get(key) as? PatchOption - if (opt == null || opt.value !is T) throw IllegalArgumentException( - "The type of the option value is not the same as the type value provided" + @Suppress("UNCHECKED_CAST") val opt = get(key) as PatchOption + if (opt.value !is T) throw InvalidTypeException( + T::class.java.canonicalName, + opt.value?.let { it::class.java.canonicalName } ?: "null" ) opt.value = value } @@ -61,7 +65,7 @@ sealed class PatchOption( var value: T? = default set(value) { if (!validator(value)) { - throw IllegalArgumentException("Illegal value: $value") + throw IllegalValueException(value) } field = value } diff --git a/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt b/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt index 3e9656a..3a41555 100644 --- a/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt +++ b/src/test/kotlin/app/revanced/patcher/patch/PatchOptionsTest.kt @@ -45,14 +45,14 @@ internal class PatchOptionsTest { @Test fun `should fail because of invalid value type`() { - assertThrows { + assertThrows { options["key1"] = 123 } } @Test fun `should fail because of an illegal value`() { - assertThrows { + assertThrows { options["key3"] = "this value is not an allowed option" } }