Retry after Exception in Groovy
Mia Lopez
In Ruby, I can write:
begin do_something # exception raised
rescue # handles error retry # restart from beginning
endIs there something similar in Groovy/Java?
I found this but maybe there is something better ?
3 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()
} 5 These days people will advise you to use ScheduledExecutorService to implement this kind of try-catch-retry functionality, as Thread.sleep() is considered outdated and potentially bad for performance. I was going to point you to a good answer on this by cletus, but can't for the life of me find it. I'll update my answer if I can dig it up.
EDIT: found it: How to retry function request after a certain time Hopefully this is of some help to you.
I can suggest to emulate kinda the same (I'm not sure about semantics of retry):
def retry(handler, c) { try { c() } catch(e) { handler(e) retry(handler, c) // restart from beginning }
}
def handler = {e -> // handles error
}
retry(handler) { do_something // exception raised
}