Skip to content

Instantly share code, notes, and snippets.

@makotan
Forked from j5ik2o/gist:2996293
Created June 27, 2012 02:04
Show Gist options
  • Save makotan/3000852 to your computer and use it in GitHub Desktop.
Save makotan/3000852 to your computer and use it in GitHub Desktop.
リトライハンドラー
case class RetryException(throwables: List[Throwable]) extends Exception(throwables.toString())
object RetryUtil {
import scala.util.control.Exception.allCatch
def retry[T](retryLimit: Int)(f: => T): T =
retry(retryLimit, 0, classOf[Throwable])(f)
def retry[T](retryLimit: Int, retryInterval: Int)(f: => T): T =
retry(retryLimit, retryInterval, classOf[Throwable])(f)
def retry[T](retryLimit: Int, catchExceptionClasses: Class[_]*)(f: => T): T =
retry(retryLimit, 0, e => catchExceptionClasses.contains(e.getClass))(f)
def retry[T](retryLimit: Int, shouldCatch: Throwable => Boolean)(f: => T): T =
retry(retryLimit, 0, shouldCatch)(f)
def retry[T](retryLimit: Int, retryInterval: Int, catchExceptionClasses: Class[_]*)(f: => T): T =
retry(retryLimit, retryInterval, e => catchExceptionClasses.contains(e.getClass))(f)
def retry[T](retryLimit: Int, retryInterval: Int, shouldCatch: Throwable => Boolean)(f: => T): T = {
@annotation.tailrec
def retry0(errors: List[Throwable], f: => T): T = {
if (errors.size == retryLimit) throw RetryException(errors)
allCatch.either(f) match {
case Right(r) => r
case Left(e) =>
if (shouldCatch(e)) {
Thread.sleep(retryInterval)
retry0(e :: errors, f)
} else throw e
}
}
retry0(Nil, f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment