处理RestClientException和HttpClientErrorException

时间:2019-05-02 07:44:56

标签: java exception

我正在通过对第三方进行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条件在处理时永远不会达到。

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

1 个答案:

答案 0 :(得分:2)

绝对不要在catch块中执行if-else来处理不同的异常。该代码不可读,执行速度可能较慢,在您的示例中,任何异常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);
}