Skip to content

Commit

Permalink
Failure Intro example #bruce #time 20m
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruce Eckel committed Jul 21, 2024
1 parent 502b588 commit 433c227
Showing 1 changed file with 32 additions and 9 deletions.
41 changes: 32 additions & 9 deletions src/test/scala/experiments/FailVarieties.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@ package experiments
import zio.*
import zio.test.*

case object ErrorObjectA:
val msg = "Failed: ErrorObjectA"
case object ErrorObjectB
extends Exception("Failed: ErrorObjectB")
case object ObjectX
case object ExceptionX extends Exception:
override def toString: String = "ExceptionX"

def failureTypes(n: Int) =
n match
case 0 =>
ZIO.fail("String fail")
case 1 =>
ZIO.fail(ObjectX)
case _ =>
ZIO.fail(ExceptionX)

object TestFailureTypes extends ZIOAppDefault:
def run =
defer:
val r0 = failureTypes(0).flip.run
printLine(s"r0: $r0").run
val r1 = failureTypes(1).flip.run
printLine(s"r1: $r1").run
val r2 = failureTypes(2).flip.run
printLine(s"r2: $r2").run

// -------------------------------------------------

def matchTo1(n: Int) =
if n == 1 then
Expand All @@ -22,7 +42,7 @@ def matchTo2(n: Int) =
if n == 2 then
defer:
printLine("Failed at 2").run
ZIO.fail(ErrorObjectA)
ZIO.fail(ObjectX)
else
defer:
printLine("Passed 2").run
Expand All @@ -32,21 +52,24 @@ def matchTo3(n: Int) =
if n == 2 then
defer:
printLine("Failed at 3").run
ZIO.fail(ErrorObjectB)
ZIO.fail(ExceptionX)
else
defer:
printLine("Passed 3").run
ZIO.succeed("Passed 3")

def completeTo(n: Int) =
defer:
val r1 = matchTo1(n).catchAll:
val r1 =
matchTo1(n).catchAll:
e => ZIO.debug(s"Caught: $e").as(e)
printLine(r1).run
val r2 = matchTo2(n).catchAll:
val r2 =
matchTo2(n).catchAll:
e => ZIO.debug(s"Caught: $e").as(e)
printLine(r2).run
val r3 = matchTo3(n).catchAll:
val r3 =
matchTo3(n).catchAll:
e => ZIO.debug(s"Caught: $e").as(e)
printLine(s"Success: $r1 $r2 $r3").run

Expand Down

0 comments on commit 433c227

Please sign in to comment.