gpt4 book ai didi

java - JAX-RS CXF 异常包装

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:19 25 4
gpt4 key购买 nike

我想向 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();
}
...
}

有办法做到这一点吗?

最佳答案

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

@Produces(MediaType.APPLICATION_JSON)

然后返回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();
}

关于java - JAX-RS CXF 异常包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11691815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com