with Monad[F] { … } Type of Monad Type of Error Inherit Monad TypeClass Implemented in cats and the other functional libraries. Abstracts over error-handling monads.
any error, potentially recovering from it, by mapping it to an * `F[A]` value. * .. */ def handleErrorWith[A](fa: F[A])(f: E => F[A]): F[A] Similar to `recoverWith` method in Future and Try
1000 [ms] sleeping..., total delay was 0 [ms] so far Error has occurred on program, retry[counter=2] after 2000 [ms] sleeping..., total delay was 1000 [ms] so far Success! Retry Retry × × ✔
to wait between attempts • Logging when handle the error You have to consider the following: Retry handling tends to be complicated Let’s take a look at a basic retry handling…
• How many times to retry • How long to wait between attempts • Logging when handle the error Action with Retry Mechanism Composition of retry policy and action
RetryPolicies.limitRetries[IO](3) |+| RetryPolicies.exponentialBackoff[IO](1.seconds) • ConstantDelay • FibonacciBackoff • FullJitter Delay Algorithm How many times to retry
and then retry every minute import retry.RetryPolicies._ val retry5times100millis = limitRetries[IO](5) |+| constantDelay[IO](100.millis) val retry1mins = constantDelay[IO](1.minute) retry5times100millis.followedBy(retry1mins)
= details match { case WillDelayAndRetry(nextDelay: FiniteDuration, retriesSoFar: Int, cumulativeDelay: FiniteDuration) => IO { logger.info( s”Error has occurred on $action, retry[counter=$retriesSoFar] after ${nextDelay.toMillis} [ms] sleeping...”) } case GivingUp(totalRetries: Int, totalDelay: FiniteDuration) => IO { logger.info( s”Giving up on $action after $totalRetries retries, finally total delay was ${totalDelay.toMillis} [ms]”) } } Logging or notification between attempts
policy, onError = logError("program") )(execute(input)) } Let’s take a look at a entire code… Retry Handling with cats-retry Action Retry Policy Error Handling
Isolation between retry policy and action • Some useful delay algorithms • Composable retry policy • Can use Monad which has the instance of MonadError