다른 웹 서비스에서 데이터를 가져 와서 브라우저로 돌아가는 webservice가 있습니다.HttpClientException을 올바르게 처리하는 방법
- 나는, 400 등 은 아래의 방법으로 웹 서비스에서 반환되는을
- (404)을 던져 원 내부 클라이언트 오류를 숨기려고합니다.
깔끔한 방법으로이 문제를 해결하는 방법은 무엇입니까?
옵션 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();
}
(또는)
내가 당신을 위해 샘플 ResponseErrorHandler를 작성했습니다 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();
}
위 코드의 문제점은 무엇입니까? 내부 예외의 상태 코드를 사용하여 내부 예외를 숨기는 새로운 예외에 넣습니다. – f1sh
Option2가보기 흉한 ... Option1이 훨씬 좋습니다. 하지만 난 당신이 오류 처리기를 분리하는 것이 좋습니다 것입니다. Spring에서 제공하는 "ResponseErrorHandler"를 구현하는 인터셉터를 생성하십시오. 모든 오류 메시지를 처리하여 코드가 훨씬 깨끗해 지도록 시도하십시오. catch 블록을 사용하지 않아도됩니다. – VelNaga
적절한 예를 들어 주시겠습니까? 감사. – Minisha