By Alvin Alexander. Last updated: May 10, 2024
As a brief Scala ZIO 2 note, if you are using ZIO.attempt
and want to show the actual exception you are working with (instead of just Throwable
), use refineToOrDie
, as shown in this example:
// this came from ZIOnomicon or the official ZIO docs
val printLine2: IO[IOException, String] =
ZIO.attempt(scala.io.StdIn.readLine())
.refineToOrDie[IOException]
and this example:
def parseInput(s: String): ZIO[Any, NumberFormatException, Int] =
ZIO.attempt(s.toInt) // ZIO[Any, Throwable, Int]
.refineToOrDie[NumberFormatException] // ZIO[Any, NumberFormatException, Int]
As I show in the comments in the second example, the error value in a plain ZIO.attempt
will be Throwable
:
ZIO.attempt(s.toInt) // ZIO[Any, Throwable, Int]
but with refineToOrDie
, you can refine that to what it actually is, a NumberFormatException
in this case:
ZIO.attempt(s.toInt) // ZIO[Any, Throwable, Int]
.refineToOrDie[NumberFormatException] // ZIO[Any, NumberFormatException, Int]