1

I wanted to handle some exceptions in ZIO using catchAll or catchSome as the below :

object Test extends App {

  def run(args: List[String]) =
    myApp.fold(_ => 1, _ => 0)

 val myApp =
    for {
      _ <- putStrLn(unsafeRun(toINT("3")).toString)
    } yield ()

def toINT(s: String): IO[IOException, Int]= {
     IO.succeed(s.toInt).map(v => v).catchAll(er =>IO.fail(er))
  }

the code succeeded in case I passed a valid format number but it's unable to handle the exception in case I passed invalid format and idea ??

NaseemMahasneh
  • 485
  • 5
  • 19
  • 1
    Why the `unsafeRun` in the middle of your IO? I think you want `for { i <- toINT("3"); _ <- putStrLn(i.toString)} yield ()` – Thilo Jul 04 '19 at 13:00

2 Answers2

3

s.toInt gets evaluated outside of the IO monad. What happens is that you evaluate s.toInt first and try to pass the result of that to IO.succeed, but an exception has already been thrown before you can pass anything to IO.succeed. The name of succeed already basically says that you are sure that whatever you pass it is a plain value that cannot fail.

The docs suggest using Task.effect, IO.effect, or ZIO.effect for lifting an effect that can fail into ZIO.

Jasper-M
  • 14,966
  • 2
  • 26
  • 37
  • I got it but you can't do map or catch without wrapping the result in a monad so now the question is what is the best wrapper to do that ? – NaseemMahasneh Jul 04 '19 at 11:52
2

Here is a program that worked for me:

val program =
  for {
    int <- toINT("3xyz")
    _ <- putStrLn(int.toString)
  } yield ()

def toINT(s: String): Task[Int] = {
  ZIO.fromTry(Try(s.toInt))
}

rt.unsafeRun(program.catchAll(t => putStrLn(t.getMessage)))
jwvh
  • 50,871
  • 7
  • 38
  • 64
  • You can simplify you `toInt` with: ```def toINT(s: String): Task[Int] = { Task.effect(s.toInt)) }```. In `ZIO`, `effect` means "import that code which can fail (you can use `Task.effect` for throwable, or `ZIO.effect` for generic error management. See that for more generic answer: https://stackoverflow.com/questions/63712633/what-is-zio-error-channel-and-how-to-get-a-feeling-about-what-to-put-in-it/63712634#63712634) – fanf42 Sep 07 '20 at 15:48