2017-09-13 253 views
0

我正在學習如何使用Retrofit2但我遇到了麻煩。使用Retrofit2處理異常

是否有任何方法來捕獲retrofit2.Retrofit上的Response對象,並在HTTP響應代碼超出範圍2xx時拋出異常?

我採取了一些JAX-RS REST服務在我的休息方法調用其他的REST API收集信息,我想處理的JAX-RS端的任何HTTP錯誤:

public class HelloRest { 

    @GET("/ping") 
    public String ping() throws IOException { 
     HelloService client = HelloServiceBuilder.getInstance(); 
     String response = client.sayHello().execute().body(); 
     LOGGER.info(response); 
    } 

    @GET ("echo/{msg}") 
    public String echo(@PathParam("msg") String msg) throws IOException { 
     HelloService client = HelloServiceBuilder.getInstance(); 
     String response = client.echo(msg).execute().body(); 
     LOGGER.info(response); 
     return response; 
    } 
} 

首先,我已經意識到​​方法拋出IOException,所以我不得不將其添加到其餘方法簽名。沒關係,我可以使用JAX-RS正確處理它。

但是,當響應代碼超出範圍2xx時,處理與HTTP響應有關的錯誤的最佳方式是什麼?

我不想寫重複的代碼塊來檢查HTTP響應代碼的任何時候,當我使用Retrofit2這樣的:

Response<String> response = client.ping().execute(); 
int responseCode = response.code(); 
if (responseCode < 200 && responseCode > 299) { 
    throws AnyException("..."); 
} 

String serverResponse = response.body(); 
... 

我可以添加一些東西到Retrofit.Builder()代碼塊來處理在這種情況下,不知何故一般的方式?

public final class HelloServiceBuilder { 

    private static final String SERVICE_URL = "..."; 

    private HelloServiceBuilder() { 
     // do nothing 
    } 

    public static HelloService getInstance() { 
     Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(SERVICE_URL) 
      .addConverterFactory(ScalarsConverterFactory.create()) 
      .HOW-TO-CHECK-RESPONSES-HERE? 
      .build(); 

     return retrofit.create(HelloService.class); 
    } 
} 

回答

0

我打算用JAX-RS創建我的休息客戶端類。它是Java的一部分,我不需要爲我的pom增加額外的依賴,像魅力一樣工作,我只需要創建一個類而不是2個或更多:

public final class MyRestClient { 
    private static Client client = ClientBuilder.newClient(); 

    public static String hello() { 
     String serviceUrl = "http://..../"; 
     String path ="hello"; 

     Response response = client 
       .target(serviceUrl) 
       .path(path) 
       .request(ExtendedMediaType.APPLICATION_UTF8) 
       .get(); 

     if (response.getStatus() == Response.Status.OK.getStatusCode()) { 
      return response.getEntity(String.class); 
     } 

     throw new WebApplicationException(response); 
    } 
}