處理

2015-06-03 58 views
7

我使用的RESTEasy一個簡單的客戶端如下的RESTEasy客戶例外:處理

public class Test { 
    public static void main(String[] args) { 
     ResteasyClient client = new ResteasyClientBuilder().build(); 
     ResteasyWebTarget target = client.target("http://localhost"); 
     client.register(new MyMapper()); 
     MyProxy proxy = target.proxy(MyProxy.class); 
     String r = proxy.getTest(); 
    } 
} 

public interface MyProxy { 
    @GET 
    @Path("test") 
    String getTest(); 
} 

@Provider 
public class MyMapper implements ClientExceptionMapper<BadRequestException>{ 

    @Override 
    public RuntimeException toException(BadRequestException arg0) { 
     // TODO Auto-generated method stub 
     System.out.println("mapped a bad request exception"); 
     return null; 
    } 

} 

服務器被配置爲一個有用的消息一起返回上一個http://localhost/test400 - Bad RequestBadRequestException正在由ClientProxy拋出。除了打包在try/catch之外,我怎樣才能讓getTest()捕獲異常並將Response的有用消息作爲字符串返回。我嘗試了各種ClientExceptionMapper實現,但看起來似乎正確。以上代碼不會撥打toException。我在這裏錯過了什麼?

我目前的解決方法是使用ClientResponseFilter,然後執行setStatus(200)並在響應實體中填入原始狀態。這樣我就避免了異常拋出。

+0

你能解釋一下你的意思嗎「服務器配置爲返回一個400 - 錯誤的請求」?我的想法是'MyProxy.getTest()'的實現實際上應該拋出一個包含有用信息的異常。然後,您將使用ExceptionMapper將該異常映射到400 - 錯誤請求響應(並且您可以將該消息包含爲響應的主體)。 – FGreg

+1

閱讀我的問題的第一句話。我正在寫一個客戶端,而不是服務器。 – gogators

回答

-1

我建議通過Jax-RS客戶端API,除非您需要使用RestEasy客戶端的功能。 (RestEasy的附帶JAX-RS,所以沒有圖書館差異)

Client client = ClientFactory.newClient(); 
WebTarget target = client.target("http://localhost/test"); 
Response response = target.request().get(); 
if (response.getStatusCode() != Response.Status.OK.getStatusCode()) { 
    System.out.println(response.readEntity(String.class)); 
    return null; 
} 
String value = response.readEntity(String.class); 
response.close(); 

之所以你的映射器不工作是因爲客戶端實際上沒有拋出異常。客戶端向代理返回一個有效的結果,並且代理正在讀取該結果,並拋出異常,這在映射器可以攔截它之後發生。

+0

這不會拋出使用代理的所有好處嗎(例如/ test在上面的例子中是硬編碼的)? 我讀到了如何讓代理拋出更有用的異常的問題。對於我來說,當實際的消息在響應中時,代理正在返回一個帶有「壞請求」的硬編碼消息的異常。是否有一個攔截器來包裝代理的異常處理? –