gpt4 book ai didi

java - Groovy 异常后重试

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:29 24 4
gpt4 key购买 nike

在 Ruby 中,我可以写:

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

Groovy/Java 中有类似的东西吗?

我找到了 this但也许有更好的东西?

最佳答案

您可以在 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()
}

关于java - Groovy 异常后重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7087185/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com