Vladimir Korenev
Vladimir Korenev

Reputation: 1166

Changing error type of ApplicativeError/MonadError

I use a library that produces a result with some custom error type. This library defines MonadError for that result type. For compatibility with the rest of my application, I'm trying to get ApplicativeThrow or MonadThrow out of that (i.e. change the error type).

I'd like to have something like this:

def changeErrorType[F[_], A, E1, E2](x: F[A])
        (convError: E1 => E2)
        (implicit ae1: MonadError[F, E1], ae2: MonadError[F, E2]): F[A] =
  x.attempt.flatMap(_.leftMap(convError).liftTo[F])

My understanding that this approach won't work because I cannot have 2 separate MonadError typeclasses for the same F but with different E1 and E2. So the signature could probably be:

def changeErrorType[F[_], G[_], A, E1, E2](x: F[A])
        (convError: E1 => E2)
        (implicit ae1: MonadError[F, E1], ae2: MonadError[G, E2]): G[A]

But I have no idea how to implement this.

Is there an idiomatic way to tackle this problem?

Update:

I can actually convert the library result to Either, then map their custom error to a Throwable, and lift Either into ApplicativeThrow. But I am wondering if the MonadError[*,CustomErrorType] instance that this library provides can be of any use if the rest of my code uses ApplicativeThrow/MonadThrow.

Upvotes: 0

Views: 109

Answers (0)

Related Questions