你需要决定你想做什么Throwable
错误不是AppError
.
如果您决定要将它们映射到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*
family
method(input).catchAll(_ => UIO.succeed(false)) // UIO[Boolean]
最后,如果您想将结果映射到Either
你可以用.either
,这会将错误从错误通道中取出并将其映射到Either[E, A]
method(input).either // UIO[Either[Throwable, Boolean]]
有一个很棒的备忘单(尽管无可否认有点过时了)here https://github.com/ghostdogpr/zio-cheatsheet as well