ZIO:为什么会收到“产生了未经检查的错误。”

问题描述 投票:0回答:1

我对ZIO中的异常处理有误解。我遵循了ZIO-Documentation

在测试类中,我运行以下代码:

  new DefaultRuntime {}.unsafeRun(
    (for {
      peopleRef <- Ref.make(Vector(People()))
      _ <- people(2).provide(Test(peopleRef)) // this throws the exception
    } yield ())
      .fold(
        err =>
          err shouldBe ServiceException("No People with id 2"), 
        _ => fail("line above should fail")
      )
  )

我以为可以使用fold函数来处理此异常,但它甚至没有到达那里。我在控制台上收到此异常:

Fiber failed.
An unchecked error was produced.
pme123.zio.examples.swapi.package$ServiceException
    at pme123.zio.examples.swapi.Swapi$Test$$anon$4.$anonfun$people$6(Swapi.scala:57)
    at zio.ZIO$MapFn.apply(ZIO.scala:2590)
    at zio.ZIO$MapFn.apply(ZIO.scala:2588)
    at zio.internal.FiberContext.evaluateNow(FiberContext.scala:709)
    at zio.Runtime.unsafeRunAsync(Runtime.scala:93)
    ....

我想念什么?

这里是一个最小的示例:

object MyApp
  extends App {

  def run(args: List[String]): ZIO[Environment, Nothing, Int] =
    program
      .fold({ error => 1 // this is not reached
      }, _ => 0)

  private lazy val program = for {
    peopleRef <- Ref.make(Vector(22))
    _ <- Test(peopleRef).people(12)
  } yield ()

  case class Test(ref: Ref[Vector[Int]]) {

    def people(id: Int): Task[Int] =
      for {
        ints <- ref.get
      } yield ints.find(_ == id) match {
        case None => throw new IllegalArgumentException(s"No People with id $id") // this is thrown
        case Some(p) =>  p
      }
  }
}

这里是完整代码:SwapiTest.scala

scala scalaz-zio
1个回答
0
投票

您需要将您的方法包装到IO.effect {}中才能说ZIO为您捕获所有异常。

def people(id: Int): Task[Int] = IO.effect {
  ...
}

请参见this文章。

© www.soinside.com 2019 - 2024. All rights reserved.