私は他のWebサービスからデータを取得してブラウザに戻すWebサービスを持っています。HttpClientExceptionを正しく処理する方法
- 私は内部クライアント・エラー
- を非表示にするには、 は、以下の方法でWebサービスから返された404、400などを投げたいです。
この問題をきちんと解決するにはどうすればよいですか?
オプション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
オプション2は醜いです...オプション1がはるかに優れています。しかし、私はエラーハンドラを分離することをお勧めします。春に提供された「ResponseErrorHandler」を実装するインターセプタを作成して、すべてのエラーメッセージを処理して、コードをもっときれいにして、tryブロックをキャッチする必要はありません。 – VelNaga
私は適切な例を教えてください。ありがとう。 – Minisha