Skip to content

Commit

Permalink
Added '$catch' function
Browse files Browse the repository at this point in the history
  • Loading branch information
rcardin committed Apr 10, 2024
1 parent b17661a commit 9b8761f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/main/scala/in/rcard/raise4s/Raise.scala
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,13 @@ def ensureNotNull[B, Error](value: B, raise: () => Error)(using r: Raise[Error])
def recover[Error, A](block: Raise[Error] ?=> () => A, recover: Error => A): A =
fold(block, ex => throw ex, recover, identity)

def recover[Error, A](block: Raise[Error] ?=> () => A, recover: Error => A, catchBlock: Throwable => A): A =
def recover[Error, A](
block: Raise[Error] ?=> () => A,
recover: Error => A,
catchBlock: Throwable => A
): A =
fold(block, catchBlock, recover, identity)

def $catch[A](block: () => A, catchBlock: Throwable => A): A =
try block()
catch case ex: Throwable => catchBlock(ex)
18 changes: 18 additions & 0 deletions src/test/scala/in/rcard/raise4s/RaiseSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,22 @@ class RaiseSpec extends AnyFlatSpec with Matchers {

actual should be(44)
}

"$catch" should "return the value if no exception is thrown" in {
val actual = $catch(
() => 42,
ex => 43
)

actual should be(42)
}

it should "return the recovery value if an exception is thrown" in {
val actual = $catch(
() => throw new RuntimeException("error"),
ex => 43
)

actual should be(43)
}
}

0 comments on commit 9b8761f

Please sign in to comment.