[英]Retry after Exception in Groovy
在 Ruby 中,我可以写:
begin
do_something # exception raised
rescue
# handles error
retry # restart from beginning
end
Groovy/Java 中有类似的东西吗?
我找到了这个,但也许有更好的东西?
您可以在 Groovy 中构建自己的辅助方法来封装此重试逻辑。
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)
}
(假设 MultipleFailureException 的定义类似于GPars 的 AsyncException )
然后在代码中,您可以按如下方式使用此方法。
retry {
errorProneOperation()
}
或者,使用不同的重试次数和错误处理行为:
retry(2, {e-> e.printStackTrace()}) {
errorProneOperation()
}
现在人们会建议你使用ScheduledExecutorService来实现这种 try-catch-retry 功能,因为Thread.sleep()
被认为是过时的并且可能对性能不利。 我打算通过 cletus 为您指出一个很好的答案,但我一生都找不到它。 如果我可以挖掘它,我会更新我的答案。
编辑:找到它: 如何在一段时间后重试 function 请求希望这对您有所帮助。
我可以建议模仿有点相同(我不确定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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.