Skip to content

Commit

Permalink
Introduce rethrowIf and rethrowUnless
Browse files Browse the repository at this point in the history
  • Loading branch information
Joseph Cooper committed Oct 26, 2021
1 parent b8d4109 commit 48112c1
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.github.michaelbull.result

/**
* If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]
* if the [predicate] returns true.
*
* @throws E if [predicate] returns true.
*/
public inline fun <V : Any?, E : Throwable> Result<V, E>.rethrowIf(
predicate: (E) -> Boolean
): Result<V, E> =
onFailure { e -> if (predicate(e)) throw e }

/**
* If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]
* only if the [predicate] returns false.
*
* @throws E if [predicate] returns false.
*/
public inline fun <V : Any?, E : Throwable> Result<V, E>.rethrowUnless(
predicate: (E) -> Boolean
): Result<V, E> = rethrowIf { e -> predicate(e).not() }
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.github.michaelbull.result

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

class RethrowTest {

class RethrowIfTest {
@Test
fun throwsIfPredicateReturnsTrue() {
val result: Result<Any, Throwable> = Err(RuntimeException())

assertFailsWith<RuntimeException> {
result.rethrowIf { _ -> true }
}
}

@Test
fun nothingThrownIfPredicateReturnsFalse() {
val result: Result<Any, Exception> = Err(NullPointerException())

result.rethrowIf { _ -> false }
}

@Test
fun doesntAlterOkValue() {
val result: Result<String, Throwable> = Ok("ok")

assertEquals(
expected = "ok",
actual = result.rethrowIf(predicate = { false }).unwrap()
)
}
}

class RethrowUnlessTest {
@Test
fun throwsIfPredicateReturnsFalse() {
val result: Result<Any, Throwable> = Err(RuntimeException())

assertFailsWith<RuntimeException> {
result.rethrowUnless { _ -> false }
}
}

@Test
fun nothingThrownIfPredicateReturnsTrue() {
val result: Result<Any, Exception> = Err(NullPointerException())

result.rethrowUnless { _ -> true }
}

@Test
fun doesntAlterOkValue() {
val result: Result<String, Throwable> = Ok("ok")

assertEquals(
expected = "ok",
actual = result.rethrowUnless(predicate = { false }).unwrap()
)
}
}
}

0 comments on commit 48112c1

Please sign in to comment.