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

标签 java rest exception jersey provider

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

相关文章:

java - 从 ArrayList<String> 中删除索引

java - 为什么我的 HTTP 响应没有显示在浏览器中?

javascript - 无法在 Restangular 中将 `all()` 与 `getList()` 一起使用?

java - HttpUrlConnection : how to get the XML response into a String?

c++ - 两种捕获异常的方法,哪一种更好?

spring-mvc - Spring Boot RestController,关于错误状态响应体,错误消息为空

java - 如何设置计步器的步数之间的最短时间?

java - 获取 "CursorIndexOutOfBoundsException "

java - RESTful JSON 与 Jersey 2.23.2

java - 如何使用异常处理来完全停止执行?