Home > Software design >  How to implement a retry logic in pattern match?
How to implement a retry logic in pattern match?

Time:08-30

This is my function that used to call another api, I want to do a retry when I got some specific exception(TimeoutException, etc) for 3 times, how can do that? Thanks for help!

 determinationService.getTax(getRequest, runID) match {
            case Success(getResponse) =>
                LOGGER.info("Following response received from determination service:")
                LOGGER.info(getTaxResponse.toString)
                    ...
            case Failure(exception) =>
                LOGGER.error(
                    "AppName:{} RunID:{} Grpc error when calling Determination service: {}",
                    Array(LoggingConstant.APP_NAME, runID, exception): _*
                )
                //do retry here
}

unit test

 val determinationServiceMock = mock[DeterminationService]
        doReturn(Failure(new TimeOutException())).when(determinationServiceMock).getTax(any(), any())

CodePudding user response:

Assuming a result type of Unit you could do:

  @tailrec
  def someDef(retry: Int = 0): Unit = {
    determinationService.getTax(getRequest, runID) match {
      case Success(getResponse) =>
        LOGGER.info("Following response received from determination service:")
        LOGGER.info(getTaxResponse.toString)
        // ...
      case Failure(exception) =>
        LOGGER.error(
          "AppName:{} RunID:{} Grpc error when calling Determination service: {}",
          Array(LoggingConstant.APP_NAME, runID, exception): _*
        )
        exception match {
          case _: TimeoutException if retry < 3 => someDef(retry   1)
          case _                                => // ...
        }
    }
  }

Note: your actual code might not be tail-recursive, just this snippet is.

  • Related