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 ?
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With