What's the Scala way to implement a retry-able call like this one?

前端 未结 14 1698
甜味超标
甜味超标 2020-11-29 16:08

Still the newbie in Scala and I\'m now looking for a way to implement the following code on it:

@Override
public void store(InputStream source, String destin         


        
14条回答
  •  [愿得一人]
    2020-11-29 17:01

    Minor improvement to printout attempt x of N

    // Returning T, throwing the exception on failure
          @annotation.tailrec
          final def retry[T](n: Int, name: String ="", attemptCount:Int = 1)(fn: => T): T = {
            logger.info(s"retry count: attempt $attemptCount of $n ....... function: $name")
            try {
              val result = fn
              logger.info(s"Succeeded: attempt $attemptCount of $n ....... function: $name")
              result
            } catch {
              case e: Throwable =>
                if (n < attemptCount) { Thread.sleep(5000 * attemptCount); retry(n, name, attemptCount+1)(fn) }
                else throw e 
            }
          }
    

提交回复
热议问题