如何解决如何不像 RuntimeException 那样在超类异常上实现重试但我的代码抛出 RestClientException?
这是我的重试代码:
let justStylesString = stylesString.split("=")[1]
登录控制台:
@Retryable(value = RestClientException.class,maxAttempts = 3,backoff = @Backoff(delay = 1000))
public <T,S> ResponseEntity<T> sendPostRequest(String url,S requestObject,Class<T> responseClazz,HttpHeaders headers) {
ResponseEntity<T> response = null;
try {
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<S> request = new HttpEntity<>(requestObject,headers);
response = restTemplate.exchange(url,HttpMethod.POST,request,responseClazz);
return response;
} catch(HttpStatusCodeException ex) {
response = new ResponseEntity(ex.getResponseBodyAsString(),ex.getStatusCode());
} catch(RestClientException rce) {
log.error("Error occurred.: {}",rce.getMessage());
throw new ServerErrorException("Exception throw");
}
return response;
}
根据我的代码,它需要重试 3 次,然后会抛出错误。但它是第一次尝试。
当我将可重试注释更改为:
Error occurred.: I/O error on POST request for "https://thirdpartyapi.com": Read timed out; nested exception is java.net.SocketTimeoutException: Read timed out
现在我的代码以正确的逻辑运行。
RuntimeException 是 RestClientException 的超类,spring-retry 仅适用于超类异常。
但我希望对我的代码有更多的控制,并为更少的异常实现重试逻辑。 RuntimeException 扩展为其他各种异常。
如何实现非超类异常的重试逻辑?
解决方法
您的代码不会抛出 RestClientException
,而是抛出 ServerErrorException
(您正在捕获它并抛出一个新的)。
因此,当您使用 RuntimeException
时,它确实有效,因为 ServerErrorException
适合。要么更改 catch 子句以抛出原始异常,要么在注释上使用 ServerErrorException
。
实际上,您可以在“值”属性中设置任何异常,而不仅仅是基本的。 此外,您可以指定 more than one exception:
@Retryable(value = {FirstException.class,SecondException.class},maxAttempts = 3,backoff = @Backoff(delay = 1000))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。