gog*_*ors 10 java jax-rs 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;
}
}
Run Code Online (Sandbox Code Playgroud)
服务器配置为返回400 - Bad Request打开http://localhost/test以及有用的消息.A BadRequestException被抛出ClientProxy.除了包装之外try/catch,我如何getTest()捕获异常并将响应的有用消息作为字符串返回.我尝试了各种各样的ClientExceptionMapper实现,但似乎可以做到正确.以上代码永远不会调用toException.我在这里错过了什么?
我目前的解决方法是使用a ClientResponseFilter然后setStatus(200)在响应实体中执行a 和填充原始状态.这样我就避免了异常抛出.
我建议使用 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();
Run Code Online (Sandbox Code Playgroud)
您的映射器不起作用的原因是客户端实际上并未抛出异常。客户端向代理返回有效结果,代理正在读取该结果,并抛出异常,这在映射器可以拦截它之后发生。
| 归档时间: |
|
| 查看次数: |
3538 次 |
| 最近记录: |