【发布时间】:2014-04-20 05:32:07
【问题描述】:
所以我正在构建一个 Web 应用程序,我们正在使用 JPA 和 Jersey 来消费/生成 JSON 数据。
我有一个自定义的“EntityException”以及一个自定义的“EntityExceptionMapper”
这是映射器:
@Provider
public class EntityExceptionMapper implements ExceptionMapper<EntityException> {
public EntityExceptionMapper() {
System.out.println("Mapper created");
}
@Override
public Response toResponse(EntityException e) {
System.out.println("This doesnt print!");
return Response.serverError().build();
}
}
我的例外:
public class EntityException extends Exception implements Serializable{
public EntityException(String message) {
super(message);
System.out.println("This prints...");
}
}
我从 REST 调用中调用它:
@POST
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public String test() throws EntityException{
throw new EntityException("This needs to be send as response!!");
//return "test";
}
我的问题是,当抛出上述异常时,我进入构造函数(打印:“This prints...”)编辑:我还得到:“Mapper created!”
但是我的响应是空的,并且我没有通过我的 toResponse 方法访问 sys。这和球衣网站上的例子真的很相似:
https://jersey.java.net/nonav/documentation/1.12/jax-rs.html#d4e435
我错过了什么??
【问题讨论】:
-
你得到这个:“映射器创建”?也许您的映射器没有被正确识别。降低 jersey 的日志记录级别以查看正在扫描的类。
-
是的,我得到了“创建的映射器”(已编辑,谢谢)
-
结果是什么?根据您的代码,您应该得到空的 500 响应。
-
如果使用 javax.ws.rs.core.Application 注册资源。您可以将 EntityExceptionMapper.class 添加到一组资源类型中。像这样的东西:classes.add(EntityExceptionMapper.class);
-
我得到一个 204 没有内容(因为我的 toResponse 似乎从未被调用),在你的评论 Loc 之后,我尝试了一些已经注册的东西(看看它是否可以工作)我尝试扩展WebApplicationException,现在它可以工作了!我将考虑使用它作为我的异常类型或注册我自己的类型。我认为这将得到解决!非常感谢。
标签: java rest exception jersey provider