recover

infix fun <Error, OtherError, A> Effect<Error, A>.recover(recover: suspend Raise<OtherError>.(error: Error) -> A): Effect<OtherError, A>(source)

Catch the raised value Error of the Effect. You can either return a value a new value of A, or short-circuit the effect by raising with a value of OtherError, or raise an exception into suspend.

import arrow.core.raise.effect
import arrow.core.raise.recover

object User
object Error

val error = effect<Error, User> { raise(Error) } // Raise(error)

val a = error.recover<Error, Error, User> { error -> User } // Success(User)
val b = error.recover<Error, String, User> { error -> raise("other-failure") } // Raise(other-failure)
val c = error.recover<Error, Nothing, User> { error -> throw RuntimeException("BOOM") } // Exception(BOOM)



inline fun <Error, A> recover(block: Raise<Error>.() -> A, recover: (error: Error) -> A): A(source)

Execute the Raise context function resulting in A or any logical error of type Error, and recover by providing a transform Error into a fallback value of type A. Base implementation of effect { f() } getOrElse { fallback() }.

fun test() {
recover({ raise("failed") }) { str -> str.length } shouldBe 6

either<Int, String> {
recover({ raise("failed") }) { str -> raise(-1) }
} shouldBe Either.Left(-1)
}

inline fun <Error, A> recover(block: Raise<Error>.() -> A, recover: (error: Error) -> A, catch: (throwable: Throwable) -> A): A(source)

Execute the Raise context function resulting in A or any logical error of type Error, and recover by providing a transform Error into a fallback value of type A, or catch any unexpected exceptions by providing a transform Throwable into a fallback value of type A,

fun test() {
recover(
{ raise("failed") },
{ str -> str.length }
) { t -> t.message ?: -1 } shouldBe 6

fun Raise<String>.boom(): Int = throw RuntimeException("BOOM")

recover(
{ boom() },
{ str -> str.length }
) { t -> t.message?.length ?: -1 } shouldBe 4
}

@JvmName(name = "recoverReified")
inline fun <T : Throwable, Error, A> recover(block: Raise<Error>.() -> A, recover: (error: Error) -> A, catch: (t: T) -> A): A(source)

Execute the Raise context function resulting in A or any logical error of type Error, and recover by providing a transform Error into a fallback value of type A, or catch any unexpected exceptions by providing a transform Throwable into a fallback value of type A,

fun test() {
recover(
{ raise("failed") },
{ str -> str.length }
) { t -> t.message ?: -1 } shouldBe 6

fun Raise<String>.boom(): Int = throw RuntimeException("BOOM")

recover(
{ boom() },
{ str -> str.length }
) { t: RuntimeException -> t.message?.length ?: -1 } shouldBe 4
}