gpt4 book ai didi

java - Jersey ExceptionMapper 中的 toResponse 不会被调用

转载 作者:搜寻专家 更新时间:2023-10-30 21:40:54 24 4
gpt4 key购买 nike

所以我正在构建一个 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();
}
}

我的异常(exception):

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。这与 Jersey 网站上的示例非常相似:

https://jersey.java.net/nonav/documentation/1.12/jax-rs.html#d4e435

我错过了什么??

最佳答案

我正在使用与部署无关的应用程序模型,因此以下对我有用:

public class MyApplication extends Application {
public Set<Class<?>> getClasses() {
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(HelloWorldResource.class);

/** you need to add ExceptionMapper class as well **/
s.add(EntityExceptionMapper.class)
return s;
}
}

关于java - Jersey ExceptionMapper 中的 toResponse 不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22413239/

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