toResponse in jersey ExceptionMapper 不會被调用

2022-09-02 20:19:21

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

我的问题是,当抛出上述异常时,我进入构造函数(打印:“此打印...”)编辑:我也得到:“映射器创建!

但是我的响应是空的,并且我没有从我的toResponse方法中获得系统。这与球衣网站上的示例非常相似:

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

我错过了什么??


答案 1

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

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

答案 2

我遇到了一个类似的问题,其中具有正确的注释,并且代码的其余部分与泽西岛的示例相同,但仍未正确注册。ExceptionMapper@Provider

好吧,事实证明,我必须手动注册我的自定义方法。由于它现在是手动注册的,因此可以安全地删除注释。ExceptionMapperHttpServletaddExceptionMapper@Provider

因此,通过以下异常映射器(我正在捕获每个将它们重新命名为400)RuntimeException

public class MyCustomExceptionHandler implements ExceptionMapper<RuntimeException> {

  @Override
  public Response toResponse(RuntimeException exception) {
    return Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();
  }
}

我不得不在我的初始化中添加第二行:

HttpServlet serviceServlet = jerseyServletFactory.create(someResource);
jerseyServletFactory.addExceptionMapper(new MyCustomExceptionHandler()); //<--

httpServer.register(serviceServlet, "/api");
httpServer.start();