【问题标题】:Handling RestClientException and HttpClientErrorException处理 RestClientException 和 HttpClientErrorException
【发布时间】:2019-05-02 07:44:56
【问题描述】:

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

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

【问题讨论】:

  • 恕我直言,spring-web 将基本状态错误处理转变为“在开发时不可见”运行时异常是愚蠢的。使用不同的库,例如 Apache 的 HttpClient。围绕它编写一个简单的包装器非常容易,可以将它变成一个方便的库,您可以在所有项目中重复使用。将对象映射器绑定到其中,您就很成功了。比 spring-web 提供的更好的错误处理。

标签: java exception


【解决方案1】:

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

像这样使用适当的 catch 块来处理它们(首先是更具体的异常,即 HttpClientErrorExceptionRestClientException 之前:

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

【讨论】:

  • 是的,我明白了。但是不同的 API 会抛出不同的异常。我还需要在 Exceptions 中有 MYAPP 信息,这样我才能知道哪个 API 抛出了哪个 Exception 并且更容易出错。
猜你喜欢
  • 2021-02-23
  • 1970-01-01
  • 2020-03-20
  • 2011-12-14
  • 1970-01-01
  • 2016-03-11
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多