Skip to content

Instantly share code, notes, and snippets.

@mccv
Created May 24, 2009 15:45
Show Gist options
  • Save mccv/117156 to your computer and use it in GitHub Desktop.
Save mccv/117156 to your computer and use it in GitHub Desktop.
package org.mccv
/**
* A marker trait indicating an exception that is recoverable.
* Note that we could make this a trait as well.
*/
class RecoverableException extends Exception
/**
* Usage of our retryable class
*/
object Retryer {
/**
* The workhorse. Runs the operation, and if successful returns the result.
* If unsuccessful calls itself recursively with a decremented run number.
*/
def tryNTimes[T](func: () => T, runNumber: Int):T = {
println("running it with " + runNumber + " tries remaining")
try{
func()
} catch {
case e:RecoverableException if runNumber > 1 => tryNTimes(func,runNumber - 1)
case e => throw e
}
}
}
object Main {
def main(args: Array[String]):Unit = {
val tries = 3;
try{
println(Retryer.tryNTimes[String](flakyMethod,tries))
}catch{
case e => println("failed after " + tries + " tries")
}
}
def flakyMethod():String = {
if(Math.random > 0.3){
throw new RecoverableException()
}else{
"foo"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment