我有一个使用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/test
返回状态码为400 - Bad Request
的响应以及有用的信息。由ClientProxy
抛出了BadRequestException
异常。除了使用try/catch
包装外,我如何使getTest()
捕获该异常并将响应的有用信息作为字符串返回?我尝试了各种ClientExceptionMapper
实现,但似乎都不正确。上面的代码从未调用toException
。我错过了什么?我的当前解决方法是使用
ClientResponseFilter
,然后执行setStatus(200)
并将原始状态放入响应实体中。这样我就避免了异常抛出。
MyProxy.getTest()
的实现实际上应该抛出一个包含有用信息的异常。然后,您将使用ExceptionMapper将该异常映射到400 - Bad Request响应(并且您可以将消息作为响应的正文)。 - FGreg