Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@florianleibert
Created January 16, 2013 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florianleibert/4552042 to your computer and use it in GitHub Desktop.
Save florianleibert/4552042 to your computer and use it in GitHub Desktop.
Retry wrapper in scala
/**
* Retries a function
* @param max the maximum retries
* @param attempt the current attempt number
* @param i the input
* @param fnc the function to wrap
* @tparam I the input parameter type
* @tparam O the output parameter type
* @return either Some(instanceOf[O]) or None if more exceptions occurred than permitted by max.
*/
def retry[I,O](max : Int, attempt : Int, i : I, fnc : (I) => O) : Option[O] = {
try {
Some(fnc(i))
} catch {
case t : Throwable => if (attempt < max) {
log.info("Retrying attempt:" + attempt)
retry(max, attempt+1, i, fnc)
} else {
log.severe("Giving up after attempts:" + attempt)
None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment