Skip to content

Commit

Permalink
refactor: migrate to custom exceptions for patch options
Browse files Browse the repository at this point in the history
  • Loading branch information
Sculas committed Aug 2, 2022
1 parent 19256b5 commit 1b42f65
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
16 changes: 10 additions & 6 deletions src/main/kotlin/app/revanced/patcher/patch/PatchOption.kt
Original file line number Diff line number Diff line change
@@ -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<PatchOption<*>> {
private val register = buildMap {
for (option in options) {
Expand All @@ -31,9 +34,10 @@ class PatchOptions(vararg val options: PatchOption<*>) : Iterable<PatchOption<*>
* Please note that using the wrong value type results in a runtime error.
*/
inline operator fun <reified T> set(key: String, value: T) {
@Suppress("UNCHECKED_CAST") val opt = get(key) as? PatchOption<T>
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<T>
if (opt.value !is T) throw InvalidTypeException(
T::class.java.canonicalName,
opt.value?.let { it::class.java.canonicalName } ?: "null"
)
opt.value = value
}
Expand Down Expand Up @@ -61,7 +65,7 @@ sealed class PatchOption<T>(
var value: T? = default
set(value) {
if (!validator(value)) {
throw IllegalArgumentException("Illegal value: $value")
throw IllegalValueException(value)
}
field = value
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ internal class PatchOptionsTest {

@Test
fun `should fail because of invalid value type`() {
assertThrows<IllegalArgumentException> {
assertThrows<InvalidTypeException> {
options["key1"] = 123
}
}

@Test
fun `should fail because of an illegal value`() {
assertThrows<IllegalArgumentException> {
assertThrows<IllegalValueException> {
options["key3"] = "this value is not an allowed option"
}
}
Expand Down

0 comments on commit 1b42f65

Please sign in to comment.