'ZIO Propagate custom exception family within Future[Either[MyException, A]], without Task which is Throwable only
I'm looking to try out ZIO but I have an exception family that looks similar to this
trait MyException extends Exception {
def errorCode: Int
}
, functions that return Future[Either[MyException, A]] and the problem I'm running into is transforming these into ZIO land. e.g.
def foo(): Future[Either[MyException, A]] = ???
def process(): ZIO[Any, MyException, Unit] =
ZIO
.fromFuture(_ => foo())
.flatMap(ZIO.fromEither[MyException, Unit]) // compiler error, expects Throwable instead of MyException
because I know foo() can return MyException, I want that to reflect in the ZIO type but it appears the type is lost during the transformation
Solution 1:[1]
First of all foo should take in an ExecutionContext so that it can use the one provided by the ZIO runtime instead of any global ExecutionContext you might have:
def foo[A]()(implicit ec: ExecutionContext): Future[Either[MyException, A]] = ???
Because ZIO still expects Future to still be able to fail with any Throwable and not just MyException, either you widen the error of process to Throwable, like:
def process(): ZIO[Any, Throwable, Unit] =
ZIO
.fromFuture(implicit ec => foo())
.flatMap(ZIO.fromEither[MyException, Unit](_)) //`fromEither` takes in an impicit in ZIO 2 so we need to be more explicit with the syntax
or you will still need to handle the Throwable with a handler like catchAll:
def process(): ZIO[Any, MyException, Unit] =
ZIO
.fromFuture(implicit ec => foo())
.catchAll {
//it depends on how you want to handle the `Throwable` as long as you only fail with `MyException`
case e: MyException => ZIO.fail(e)
case _ => ZIO.succeed(Right())
}.flatMap(ZIO.fromEither[MyException, Unit](_))
without Task which is Throwable only
I think you might be confusing the contravariant ZIO environment with the covariant error type parameter. The process you want can fail with MyException only but the lifted Future within can fail with any Throwable including MyException. You can read more about variances here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
