繁体   English   中英

RESTEasy客户端异常处理

[英]RESTEasy Client Exception Handling

我有一个使用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;
    }

}

服务器配置400 - Bad Requesthttp://localhost/test上返回400 - Bad Request以及有用的消息。 ClientProxy正在抛出BadRequestException 除了包装在try/catch ,我如何让getTest()捕获异常并将响应的有用消息作为字符串返回。 我尝试了各种ClientExceptionMapper实现,但似乎可以做到正确。 上面的代码不会调用toException 我在这里错过了什么?

我目前的解决方法是使用ClientResponseFilter ,然后执行setStatus(200)并将原始状态填充到响应实体中。 这样我就避免了异常抛出。

不推荐使用Resteasy中的ClientExceptionMapper(参见java docs

resteasy-client模块中的JAX-RS 2.0客户端代理框架不使用org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper。

尝试使用ExceptionMapper,如下所示:

import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class MyMapper implements ExceptionMapper<ClientErrorException> {

    @Override
    public Response toResponse(ClientErrorException e) {
        return Response.fromResponse(e.getResponse()).entity(e.getMessage()).build();
    }
}

问候,

我建议您浏览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();

您的映射器不起作用的原因是因为客户端实际上没有抛出异常。 客户端正在向代理返回一个有效的结果,代理正在读取它,并抛出异常,这在mapper可以拦截它之后发生。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM