[英]Jersey Custom Exception Message
I've written a Jersey Server application and a Client application which is consuming the provided REST Services. 我已经编写了使用提供的REST服务的Jersey Server应用程序和Client应用程序。 But I've problems to pass exception messages from server to client. 但是我在将异常消息从服务器传递到客户端时遇到了问题。 Currently I've implemented it like: 目前,我已将其实现为:
Server WS Method: 服务器WS方法:
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public TestModel doTest(){
throw new NotImplementedException("[doTest] is not implemented yet");
}
NotImplementedException: NotImplementedException:
public class NotImplementedException extends WebApplicationException{
public NotImplementedException(){
super(Response.status(Response.Status.NOT_IMPLEMENTED)
.entity("The operation you've called is not implemented yet").type(MediaType.APPLICATION_JSON).build());
}
public NotImplementedException(String message){
super(Response.status(Response.Status.BAD_GATEWAY).entity(message).type(MediaType.APPLICATION_JSON).build());
}
}
Client: 客户:
public static TestModel doTest() throws Exception{
try {
Client client = getClient();
WebTarget webTarget = client.target("server..../");
WebTarget getGuTarget = webTarget.path("test");
Invocation.Builder ib = getGuTarget.request(MediaType.APPLICATION_JSON);
TestModel response = ib.get(TestModel.class); //here exception is thorwn
return response;
} catch (Exception e) {
throw e;
}
}
The exception caught on the Client looks like: 客户端捕获的异常如下所示:
javax.ws.rs.ServerErrorException: HTTP 502 Bad Gateway
at org.glassfish.jersey.client.JerseyInvocation.createExceptionForFamily(JerseyInvocation.java:1029)
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1009)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:799)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:91)
Unfortunately I'm not able to receive the "[doTest] is not implemented yet" Message on the client. 不幸的是,我无法在客户端上收到“ [doTest]尚未实现”消息。 How I can get this message? 我如何获得此消息?
When I test the webservice I receive the correct message in the body. 当我测试Web服务时,我在体内收到正确的消息。 Unfortunately I don't know how I can access it via jersey? 不幸的是,我不知道如何通过球衣访问它?
Thanks. 谢谢。
You can use an ExceptionMapper for custom exceptions: https://jersey.java.net/apidocs/2.11/jersey/javax/ws/rs/ext/ExceptionMapper.html 您可以将ExceptionMapper用于自定义异常: https : //jersey.java.net/apidocs/2.11/jersey/javax/ws/rs/ext/Exception/Mapper.html
Otherwise, Jersey tries to map exceptions as good as it can on its own. 否则,Jersey会尝试尽可能独立地映射异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.