春季重试例外处理执行行为
我正在尝试采用最佳方法来包装春季重返
@retryable
围绕外部服务调用的注释。这是我的代码:
@Retryable(exclude = HttpClientErrorException.BadRequest.class, value = RestClientException.class)
private ResponseEntity<Item> retrieveItemById(String id)
{
HttpHeaders headers = new HttpHeaders();
try {
return restTemplate.exchange(httpConnectionProperties.getBaseUrl() + "/items",
HttpMethod.GET, new HttpEntity<>(item, headers), Item.class, id);
}
catch (RestClientException e) {
log.error("Exception occurred while retrieving an item" , e);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
我有几个问题,即RESTCLIENTEXCEPTION
发生时会发生什么:
- 是在
retry
启动之前执行的捕获块,还是在捕获之前重试块执行?我需要一个恢复块吗? - 可能更多的例外处理问题 - 是否有一种方法可以区分实际的重试值得的场景(服务暂时降低,网络问题,I/O错误等)与由于上述情况不存在项目而导致的例外情况?
I am trying to get to the best way to wrap spring-retry
@Retryable
annotation around external service call. Here is my code:
@Retryable(exclude = HttpClientErrorException.BadRequest.class, value = RestClientException.class)
private ResponseEntity<Item> retrieveItemById(String id)
{
HttpHeaders headers = new HttpHeaders();
try {
return restTemplate.exchange(httpConnectionProperties.getBaseUrl() + "/items",
HttpMethod.GET, new HttpEntity<>(item, headers), Item.class, id);
}
catch (RestClientException e) {
log.error("Exception occurred while retrieving an item" , e);
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
I have a few questions on what happens when a RestClientException
occurs :
- Is the catch block executed before
retry
kicks in or does the retry kicks in before the catch block execution? Do I need a recovery block? - Probably more of an exception handling question - Is there a way to differentiate between an actual retry worthy scenario (service momentarily down, network issues, I/O error etc.) vs exception occurring due to lack of presence of an item in the above case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您正在捕获和“处理”例外,因此重试被禁用;仅当方法引发异常时,重试才能工作。
要更改结果(而不是在恢复耗尽时将异常扔给呼叫者,您需要一个
@Recover
方法。不可重复的例外将直接出现在那里;您可以拥有多个
@recover < /代码>用于不同异常类型的方法,或一种通用类型,您可以自己检查异常类型。
Since you are catching and "handling" the exception, retry is disabled; retry will only work if the method throws an exception.
To change the result (instead of throwing the exception to the caller when retries are exhausted, you need a
@Recover
method.Not retryable exceptions will go straight there; you can have multiple
@Recover
methods for different exception types, or one generic one and you can check the exception type yourself.