Skip to content

Commit

Permalink
Create new extension function rethrow along with tests for it
Browse files Browse the repository at this point in the history
  • Loading branch information
Joseph Cooper committed Oct 11, 2021
1 parent b8d4109 commit 257f08c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.github.michaelbull.result

/**
* If the [Result] is [Err] and contains a [Throwable], throws the [error][Err.error]
* if it is an instance of [E].
*
* @throws E if [error][Err.error] is an instance of [E]
*/
public inline fun <V: Any?, reified E : Throwable> Result<V, Throwable?>.rethrow()
: Result<V, Throwable?> =
mapError { e -> if (e is E) throw e else e }
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.github.michaelbull.result

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

class RethrowTest {

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

assertFailsWith<RuntimeException> {
result.rethrow<Any, Exception>()
}
}

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

result.rethrow<Any, IllegalArgumentException>()
}

@Test
fun nothingThrownIfErrorIsNull() {
val result: Result<Any, Throwable?> = Err(null)

result.rethrow<Any, Throwable>()
}

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

assertEquals(
expected = "ok",
actual = result.rethrow<String, Exception>().unwrap()
)
}

}

0 comments on commit 257f08c

Please sign in to comment.