【问题标题】:JAX-RS CXF Exception wrappingJAX-RS CXF 异常包装
【发布时间】:2012-07-28 01:41:51
【问题描述】:

我想在 CXF (2.6.1) 中添加一个 ExceptionMapper,它不仅可以传达响应代码,还可以以有效负载格式发送异常(我现在使用的是 JSON)。

@Provider
public class CustomExceptionMapper
        implements
            ExceptionMapper<MyException>
{
...
@Override
public Response toResponse(MyException mex)
{
//I need something here which can convert mex object to JSON and ship it in response
// I want this to be de-serialized on client

//the following returns the status code
return Response.status(Response.Status.BAD_REQUEST).build();
}
...
}

有没有办法做到这一点?

【问题讨论】:

    标签: java cxf jax-rs cxfrs


    【解决方案1】:

    您可能需要使用 @Produces 将您的对象序列化为 JSON,例如:

    @Produces(MediaType.APPLICATION_JSON)
    

    然后return Response.ok().entity(OBJECT).build();

    测试服务的方式:

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    ClientResponse response = service.path(ADDRESS).type("application/json").get(ClientResponse.class);
    String s = response.getEntity(String.class);
    System.out.println(s); 
    
    private static URI getBaseURI() {
            return UriBuilder.fromUri(SERVER ADDRESS).build();
    }
    

    【讨论】:

    • 感谢您的回复。但我想返回状态 500 或 400 但不是 200。有办法吗?
    • 想通了。就是这样 Response.ok(mex,MediaType.APPLICATION_JSON).status(Response.Status.BAD_REQUEST).build();
    • 在客户端,我必须添加拦截器吗?似乎我的 servlet 阻止了非 200 响应
    • 不,它不应该被阻止。您是否使用 Tomcat 作为您的 servlet?
    • 是的,它是 tomcat。是的.. 我得到一个 org.apache.cxf.jaxrs.client.ServerWebApplicationException 类型的异常我如何从中获得“MyException”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多