开发者

Retry after Exception in Groovy

开发者 https://www.devze.com 2023-03-29 02:31 出处:网络
In Ruby, I can write: begin do_something # exception raised rescue # handles error retry# restart from beginning

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 thi开发者_StackOverflow中文版s 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()
}


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消