Bohtvaroh

Blogger - FPOWJPWB - Retry in Scala

Jul 27th, 2012
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.79 KB | None | 0 0
  1. object retry {
  2.   def apply[Result](operation: () => Result,
  3.                     checker: Result => Boolean,
  4.                     preRetry: () => Any = null,
  5.                     times: Int = 1,
  6.                     errorMessage: String = "Retries exhausted"): Result = {
  7.     val (operationResult, operationException): (Result, Exception) = try {
  8.       (operation(), null)
  9.     } catch {
  10.       case e: Exception => (null, e)
  11.     }
  12.  
  13.     if (operationException == null && checker(operationResult))
  14.       operationResult
  15.     else {
  16.       if (times > 0) {
  17.         if (preRetry != null) preRetry()
  18.         apply(operation, checker, preRetry, times - 1, errorMessage)
  19.       } else
  20.         throw
  21.           if (operationException != null) operationException else new Exception(errorMessage)
  22.     }
  23.   }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment