catch

inline fun <E, T : Throwable, A> Either<Throwable, A>.catch(catch: Raise<E>.(T) -> A): Either<E, A>(source)

Variant of Either.catchOrThrow constructor that allows for working with Either<Throwable, A> by transforming or recovering from Throwable as T in the Either.Left side. This API is the same as recover. This is useful when working with results of Either.catch since this API offers a reified variant.

import arrow.core.Either
import arrow.core.catch
import io.kotest.assertions.throwables.shouldThrowUnit
import io.kotest.matchers.shouldBe

fun test() {
val left: Either<Throwable, Int> = Either.catch { throw RuntimeException("Boom!") }

val caught: Either<Nothing, Int> = left.catch { _: RuntimeException -> 1 }
val failure: Either<String, Int> = left.catch { _: RuntimeException -> raise("failure") }

shouldThrowUnit<RuntimeException> {
val caught2: Either<Nothing, Int> = left.catch { _: IllegalStateException -> 1 }
}

caught shouldBe Either.Right(1)
failure shouldBe Either.Left("failure")
}