【发布时间】:2015-08-18 07:05:29
【问题描述】:
我有一个使用 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 以及有用的消息。 BadRequestException 正在被 ClientProxy 抛出。除了包裹在try/catch 中之外,我怎样才能让getTest() 捕获异常并将响应的有用消息作为字符串返回。我尝试了各种ClientExceptionMapper 实现,但似乎都做对了。上面的代码从来没有调用过toException。我在这里错过了什么?
我目前的解决方法是使用ClientResponseFilter,然后执行setStatus(200) 并将原始状态填充到响应实体中。这样我就避免了异常抛出。
【问题讨论】:
-
您能解释一下“服务器配置为返回 400 - 错误请求”是什么意思吗?我的想法是
MyProxy.getTest()的实现实际上应该抛出一个包含有用消息的异常。然后,您将使用 ExceptionMapper 将该异常映射到 400 - Bad Request 响应(您可以将消息作为响应的正文包含在内)。 -
阅读我的问题的第一句话。我正在编写客户端,而不是服务器。