Guest User

Untitled

a guest
Nov 18th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1.  
  2. case class RetryException(throwables: List[Throwable]) extends Exception(throwables.toString())
  3.  
  4. object RetryUtil {
  5.  
  6. import scala.util.control.Exception.allCatch
  7.  
  8. def retry[T](retryLimit: Int)(f: => T): T =
  9. retry(retryLimit, 0, classOf[Throwable])(f)
  10.  
  11. def retry[T](retryLimit: Int, retryInterval: Int)(f: => T): T =
  12. retry(retryLimit, retryInterval, classOf[Throwable])(f)
  13.  
  14. def retry[T](retryLimit: Int, catchExceptionClasses: Class[_]*)(f: => T): T =
  15. retry(retryLimit, 0, e => catchExceptionClasses.exists(_.isAssignableFrom(e.getClass)))(f)
  16.  
  17. def retry[T](retryLimit: Int, shouldCatch: Throwable => Boolean)(f: => T): T =
  18. retry(retryLimit, 0, shouldCatch)(f)
  19.  
  20. def retry[T](retryLimit: Int, retryInterval: Int, catchExceptionClasses: Class[_]*)(f: => T): T =
  21. retry(retryLimit, retryInterval, e => catchExceptionClasses.exists(_.isAssignableFrom(e.getClass)))(f)
  22.  
  23. def retry[T](retryLimit: Int, retryInterval: Int, shouldCatch: Throwable => Boolean)(f: => T): T = {
  24. @annotation.tailrec
  25. def retry0(errors: List[Throwable], f: => T): T = {
  26. allCatch.either(f) match {
  27. case Right(r) => r
  28. case Left(e) =>
  29. if (shouldCatch(e)) {
  30. if (errors.size < retryLimit - 1) {
  31. Thread.sleep(retryInterval)
  32. retry0(e :: errors, f)
  33. } else {
  34. throw RetryException(e :: errors)
  35. }
  36. } else throw e
  37. }
  38. }
  39. retry0(Nil, f)
  40. }
  41.  
  42. }
Add Comment
Please, Sign In to add comment