java - 处理 RestClientException 和 HttpClientErrorException
问题描述
我通过向第 3 方进行 RESTFul 调用(Spring RestTemplate)来处理一些请求。在代码中,我正在尝试处理以下条件。
catch (final Exception ex) {
if (ex instanceof HttpClientErrorException) {
HttpClientErrorException hcee = (HttpClientErrorException)ex;
if(hcee.getStatusCode() == NOT_FOUND) {
throw new MyRecordNotFoundException(hcee);
}
}else {
handleRestClientException(ex, Constants.MYAPP);
}
这是 handleRestClientException 实现
protected Exception handleRestClientException(Exception ex, String serviceName) throws Exception{
if (ex instanceof RestClientResponseException) {
RestClientResponseException rcre = (RestClientResponseException) ex;
throw new RestClientResponseException(serviceName, rcre.getRawStatusCode(),
rcre.getStatusText(), rcre.getResponseHeaders(), rcre.getResponseBodyAsByteArray(), null);
} else {
throw new Exception(serviceName, ex);
}
但是所有 org.springframework.web.client.RestTemplate.getForObject(String url, Class responseType, Map urlVariables) 都会抛出 RestClientException
哪个是 HttpClientErrorException 的父级
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.RuntimeException
org.springframework.core.NestedRuntimeException
org.springframework.web.client.RestClientException
org.springframework.web.client.RestClientResponseException
org.springframework.web.client.HttpStatusCodeException
org.springframework.web.client.HttpClientErrorException
因此,我的代码中提到的 if 条件在处理时永远不会达到。
你能帮我有效地处理这个层次结构中的每个异常吗?
解决方案
您永远不应该if-else
在 catch 块中处理不同的异常。该代码不可读,执行速度可能较慢,并且在您的示例中,任何异常(除了HttpClientErrorException
)都像RestClientException
.
像这样使用适当的 catch 块处理它们(首先是更具体的异常,即HttpClientErrorException
在之前RestClientException
:
catch (HttpClientErrorException hcee) {
if (hcee.getStatusCode() == NOT_FOUND) {
throw new MyRecordNotFoundException(hcee);
}
}
catch (final RestClientException rce) {
handleRestClientException(rce, Constants.MYAPP);
}
推荐阅读
- asp.net - ASP NET Identity 为什么要加密规范化的用户名而不是用户名?
- c++ - 找不到 -lglfw3 的库
- javascript - 获取 select 的值并将其绑定到对象
- bash - 内存在 Kubernetes pod 上超时累积,导致 JVM 无法启动
- r - 在 R 中的函数内使用 unnest_tokens() 会导致错误
- go - 数据流作业在执行时间过长后失败
- android - 如何使用 Room 和 Java 来管理外键
- javascript - 如何循环嵌套的json?
- azure - 如何在 Cosmos DB 中执行“分组依据”查询?
- python - 是否可以使用我的机器人在 discord.py 中附加大于 150Mb 的文件