Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry after Exception in Groovy

In Ruby, I can write:

begin
  do_something # exception raised
rescue
   # handles error
   retry  # restart from beginning
end

Is there something similar in Groovy/Java?

I found this but maybe there is something better ?

like image 463
Nicolas Modrzyk Avatar asked Aug 17 '11 01:08

Nicolas Modrzyk


1 Answers

You could build up your own helper method in Groovy to encapsulate this retry logic.

def retry(int times = 5, Closure errorHandler = {e-> log.warn(e.message,e)}
     , Closure body) {
  int retries = 0
  def exceptions = []
  while(retries++ < times) {
    try {
      return body.call()
    } catch(e) {
      exceptions << e
      errorHandler.call(e)
    }        
  }
  throw new MultipleFailureException("Failed after $times retries", exceptions)
}

(Assuming a definition of MultipleFailureException similar to GPars' AsyncException)

then in code, you could use this method as follows.

retry {
   errorProneOperation()
}

or, with a different number of retries and error handling behaviour:

retry(2, {e-> e.printStackTrace()}) {
  errorProneOperation()
}
like image 50
winstaan74 Avatar answered Oct 28 '22 18:10

winstaan74