2017-09-22 4 views
0

私は他のWebサービスからデータを取得してブラウザに戻すWebサービスを持っています。HttpClientExceptionを正しく処理する方法

  1. 私は内部クライアント・エラー
  2. を非表示にするには、 は、以下の方法で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(); 
    } 
+0

上記コードの問題点を教えてください。内部例外からのステータスコードを使用して、内部例外を隠す新しい例外に置きます。 – f1sh

+0

オプション2は醜いです...オプション1がはるかに優れています。しかし、私はエラーハンドラを分離することをお勧めします。春に提供された「ResponseErrorHandler」を実装するインターセプタを作成して、すべてのエラーメッセージを処理して、コードをもっときれいにして、tryブロックをキャッチする必要はありません。 – VelNaga

+0

私は適切な例を教えてください。ありがとう。 – Minisha

答えて

0

オプション、

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); 
    } 
} 
} 

注:これは一般的ですResponseErあなたのrestTemplateのrorHandlerと、restTemplateによってスローされたすべての例外をキャッチします。あなたはtryメソッドを呼び出す必要はなく、 "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(); 
} 

は、だからあなたの方法は、今美しく見ていない、このようなあなたのクライアントクラスをリファクタリングすることができますか?提案は大歓迎です。

+0

この質問の投票を削除できますか?私は、質問はかなり合理的だと思います。そして当初、私は私が探していたものについてはっきりしていませんでした。申し訳ありません – Minisha

+0

@MinishaMurugan私はそれをした誰かの質問をd​​ownvoteしませんでした。しかし、あなたは正しい答えを持っていても問題ありません。 – VelNaga

関連する問題