diff --git a/result-object/src/main/kotlin/com/github/navikt/tbd_libs/result_object/Result.kt b/result-object/src/main/kotlin/com/github/navikt/tbd_libs/result_object/Result.kt index 8f3f215..c64779a 100644 --- a/result-object/src/main/kotlin/com/github/navikt/tbd_libs/result_object/Result.kt +++ b/result-object/src/main/kotlin/com/github/navikt/tbd_libs/result_object/Result.kt @@ -5,6 +5,11 @@ sealed interface Result { data class Error(val error: String, val cause: Throwable? = null) : Result } +fun Result.getOrThrow() = when (this) { + is Result.Error -> throw RuntimeException(error, cause) + is Result.Ok -> value +} + fun Result.map(whenOk: (T) -> Result) = when (this) { is Result.Error -> this is Result.Ok -> whenOk(value) @@ -18,6 +23,14 @@ fun Result.fold( is Result.Ok -> whenOk(value) } +fun tryCatch(block: () -> R): Result { + return try { + block().ok() + } catch (err: Exception) { + err.error(err.message.toString()) + } +} + fun List>.flatten(): Result> { return fold(Result.Ok(emptyList()) as Result>) { acc, result -> result.fold( diff --git a/result-object/src/test/kotlin/com/github/navikt/tbd_libs/result_object/ResultTest.kt b/result-object/src/test/kotlin/com/github/navikt/tbd_libs/result_object/ResultTest.kt index 89e1a85..a4954f4 100644 --- a/result-object/src/test/kotlin/com/github/navikt/tbd_libs/result_object/ResultTest.kt +++ b/result-object/src/test/kotlin/com/github/navikt/tbd_libs/result_object/ResultTest.kt @@ -1,6 +1,7 @@ package com.github.navikt.tbd_libs.result_object import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.assertThrows import org.junit.jupiter.api.Test class ResultTest { @@ -89,6 +90,31 @@ class ResultTest { } } + @Test + fun `get or throw`() { + assertThrows { + "Error msg".error().getOrThrow() + }.also { assertEquals("Error msg", it.message) } + + assertEquals("Hei", "Hei".ok().getOrThrow()) + } + + @Test + fun tryCatching() { + tryCatch { + "Hei, på deg!" + }.also { + it as Result.Ok + assertEquals("Hei, på deg!", it.value) + } + tryCatch { + error("Whoops!") + }.also { + it as Result.Error + assertEquals("Whoops!", it.error) + } + } + private fun testfun(feil: Boolean): Result { return when (feil) { true -> Result.Error("Denne gir feil altså!")