gpt4 book ai didi

java - 处理 RestClientException 和 HttpClientErrorException

转载 作者:行者123 更新时间:2023-12-01 19:39:13 27 4
gpt4 key购买 nike

我通过向第 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 条件在处理时永远不会达到。

你能帮我有效地处理这个层次结构中的每个异常吗?

最佳答案

您永远不应该在 catch block 中执行 if-else 来处理不同的异常。该代码不可读,执行速度可能较慢,并且在您的示例中,任何异常(HttpClientErrorException 除外)都像 RestClientException 一样处理。

使用适当的 catch block 来处理它们,如下所示(首先是更具体的异常,即 RestClientException 之前的 HttpClientErrorException:

catch (HttpClientErrorException hcee) {
if (hcee.getStatusCode() == NOT_FOUND) {
throw new MyRecordNotFoundException(hcee);
}
}
catch (final RestClientException rce) {
handleRestClientException(rce, Constants.MYAPP);
}

关于java - 处理 RestClientException 和 HttpClientErrorException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55947798/

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