如何正确处理HttpClientException

时间:2017-09-22 14:24:14

标签: java spring apache-httpclient-4.x

我有一个web服务,从其他web服务获取数据并返回浏览器。

  1. 我想隐藏内部客户端错误
  2. 想扔掉404,400等 通过以下方法从Web服务返回。
  3. 如何以一种简洁的方式解决这个问题?

    选项1或选项2是干净的方式吗?

    选项1

    public <T> Optional<T> get(String url, Class<T> responseType) {
            String fullUrl = url;
            LOG.info("Retrieving data from url: "+fullUrl);
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
                headers.add("Authorization", "Basic " + httpAuthCredentials);
    
                HttpEntity<String> request = new HttpEntity<>(headers);
                ResponseEntity<T> exchange = restTemplate.exchange(fullUrl, HttpMethod.GET, request, responseType);
                if(exchange !=null)
                    return Optional.of(exchange.getBody());
            } catch (HttpClientErrorException e) {
                LOG.error("Client Exception ", e);
                throw new HttpClientError("Client Exception: "+e.getStatusCode());
            }
             return Optional.empty();
      }
    

    (或)

    选项2

    public   <T> Optional<T> get(String url, Class<T> responseType) {
            String fullUrl = url;
            LOG.info("Retrieving data from url: "+fullUrl);
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
                headers.add("Authorization", "Basic " + httpAuthCredentials);
    
                HttpEntity<String> request = new HttpEntity<>(headers);
                ResponseEntity<T> exchange = restTemplate.exchange(fullUrl, HttpMethod.GET, request, responseType);
                if(exchange !=null)
                    return Optional.of(exchange.getBody());
                throw new RestClientResponseException("", 400, "", null, null, null);
            } catch (HttpStatusCodeException e) {
                LOG.error("HttpStatusCodeException ", e);
                throw new RestClientResponseException(e.getMessage(), e.getStatusCode().value(), e.getStatusText(), e.getResponseHeaders(), e.getResponseBodyAsByteArray(), Charset.defaultCharset());
            }
            return Optional.empty();
        }
    

1 个答案:

答案 0 :(得分:1)

我已为您编写了一个ResponseErrorHandler示例,

public class RestTemplateClientErrorHandler implements ResponseErrorHandler {

private static final Logger logger = LoggerFactory.getLogger(RestTemplateClientErrorHandler.class);

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
    return RestUtil.isError(clientHttpResponse.getStatusCode());
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {
    String responseBody = "";
    if(clientHttpResponse != null && clientHttpResponse.getBody() != null){
        responseBody = IOUtils.toString(clientHttpResponse.getBody());
    }
    switch(clientHttpResponse.getRawStatusCode()){
        case 404:
            logger.error("Entity not found. Message: {}. Status: {} ",responseBody,clientHttpResponse.getStatusCode());
            throw new RestClientResponseException(responseBody);
        case 400:
            logger.error("Bad request for entity. Message: {}. Status: {}",responseBody, clientHttpResponse.getStatusCode());
            throw new RestClientResponseException(StringUtils.EMPTY, 400,StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY);
        default:
            logger.error("Unexpected HTTP status: {} received when trying to delete entity in device repository.", clientHttpResponse.getStatusCode());
            throw new RestClientResponseException(responseBody);
    }

}

public static class RestUtil {

    private RestUtil() {
        throw new IllegalAccessError("Utility class");
    }

    public static boolean isError(HttpStatus status) {
        HttpStatus.Series series = status.series();
        return HttpStatus.Series.CLIENT_ERROR.equals(series)
                || HttpStatus.Series.SERVER_ERROR.equals(series);
    }
}
}

注意:这是restTemplate的常见ResponseErrorHandler,它将捕获restTemplate抛出的所有异常,你不需要try,catch块在每个方法中,你不需要捕获“HttpStatusCodeException”或任何其他异常。

请使用以下代码注册此ErrorHandler。

RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new RestTemplateClientErrorHandler());

您还可以找到示例here

您可以像这样重构您的客户端类,

public <T> Optional<T> get(String url, Class<T> responseType) {
    String fullUrl = url;
    LOG.info("Retrieving data from url: "+fullUrl);
        HttpHeaders headers = new HttpHeaders();

       headers.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
        headers.add("Authorization", "Basic " + httpAuthCredentials);

        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<T> exchange = restTemplate.exchange(fullUrl, HttpMethod.GET, request, responseType);
        if(exchange !=null)
            return Optional.of(exchange.getBody());
     return Optional.empty();
}

所以你的方法现在看起来不漂亮吗?建议欢迎。