我有下面的代码:
import zio._
import scala.concurrent.Future
case class AppError(description: String) extends Throwable
// legacy-code imitation
def method(x: Int): Task[Boolean] = {
Task.fromFuture { implicit ec => Future.successful(x == 0) }
}
def handler(input: Int): IO[AppError, Int] = {
for {
result <- method(input)
_ <- IO.fail(AppError("app error")).when(result)
} yield input
}但是这段代码不能编译,因为编译器说结果类型是:
ZIO[Any, Throwable, Int]
如何从任务(我调用method)转换为IO?
发布于 2020-07-13 00:23:37
您需要决定如何处理非AppError的Throwable错误。
如果您决定要将它们映射到AppError,您可以这样做:
method(input).mapError {
case ae: AppError => ae
case other => AppError(other.getMessage)
}如果您想要细化这些错误并只保留那些为AppError的错误,那么您可以使用refine*运算符系列之一,它将保留与谓词匹配的错误,否则将终止纤程。
method(input).refineToOrDie[AppError] // IO[AppError, Boolean]
// Or
method(input).refineOrDie { case ae: AppError => ae } // IO[AppError, Boolean]或者,如果您希望假设来自method的所有错误都被认为是“纤程终止”,那么您可以使用.orDie来吸收错误并终止纤程:
method(input).orDie // UIO[Boolean]或者,如果您想从错误中恢复并以不同的方式处理它,那么您可以使用catch*系列
method(input).catchAll(_ => UIO.succeed(false)) // UIO[Boolean]最后,如果希望将结果映射到Either中,可以使用.either,它会将错误从错误通道中删除并映射到Either[E, A]中
method(input).either // UIO[Either[Throwable, Boolean]]还有一个很棒的小抄(尽管无可否认有点过时),here
https://stackoverflow.com/questions/62860131
复制相似问题