JAX-RS CXF Exception wrapping

丶灬走出姿态 提交于 2019-12-24 18:39:58

问题


I would like to add an ExceptionMapper to CXF (2.6.1) which not only communicates the Response code, but also ships the exception in the payload format (I'm using JSON for now).

@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();
}
...
}

Is there a way to do this ?


回答1:


You may need to use @Produces to serialize your object to JSON like:

@Produces(MediaType.APPLICATION_JSON)

And then return Response.ok().entity(OBJECT).build();

The way that you can test your service:

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();
}


来源:https://stackoverflow.com/questions/11691815/jax-rs-cxf-exception-wrapping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!