exception - JAX-RS 异常映射器在 Grizzly 容器中不起作用

标签 exception jax-rs jersey-2.0 grizzly exceptionmapper

与团队一起开发 Jersey Web 应用程序,随着项目变得越来越大,我们决定从 Tomcat 切换到 Grizzly,以允许在不同的端口号上部署项目的部分内容。我现在发现,我们的自定义异常处理现在无法工作,相反我总是得到灰白色的 html 页面。

异常示例:

public class DataNotFoundException extends RuntimeException{

private static final long serialVersionUID = -1622261264080480479L;

public DataNotFoundException(String message) {
    super(message);
    System.out.println("exception constructor called"); //this prints
 }
}

映射器:

@Provider
public class DataNotFoundExceptionMapper implements ExceptionMapper<DataNotFoundException>{

public DataNotFoundExceptionMapper() {
    System.out.println("mapper constructor called"); //doesnt print
}

@Override
public Response toResponse(DataNotFoundException ex) {
    System.out.println("toResponse called"); //doesnt print
    ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), 404, "No documentation yet."); 
    return Response.status(Status.NOT_FOUND)
            .entity(errorMessage)
            .build();
      //ErrorMessage is a simple POJO with 2 string and 1 int field
 }

}

我不确定问题根源在哪里,如果需要,我可以提供更多信息/代码。有什么问题,我可以尝试什么?

编辑:

主类:

public class Main {

/**
 * Main method.
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {

...

    List<ServerInfo> serverList = new ArrayList<ServerInfo>();

    serverList.add(new ServerInfo(
            "api",8450,
            new ResourceConfig().registerClasses(
                    the.package.was.here.ApiResource.class)
            ));             

    for(ServerInfo server : serverList) {
        server.start();
    }

    System.out.println("Press enter to exit...");
    System.in.read();

    for(ServerInfo server : serverList) {
        server.stop();
    }

}
}

编辑2: 基于this我尝试过使用这个 ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true" 属性,但效果不大。当异常发生时,我仍然得到 html grizzly 页面,但现在我在页面正文中看到我的异常(+堆栈跟踪)。

最佳答案

您仅为整个应用程序注册一个资源类

new ResourceConfig().registerClasses(
        eu.arrowhead.core.api.ApiResource.class
)

映射器也需要注册

new ResourceConfig().registerClasses(
        eu.arrowhead.core.api.ApiResource.class,
        YourMapper.class)
)

您还可以使用包扫描,如果它们用 @Path@Provider 注释,它将拾取所有类并自动注册它们

new ResourceConfig().packages("the.packages.to.scan")

关于exception - JAX-RS 异常映射器在 Grizzly 容器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38098391/

相关文章:

java - 返回 http 状态 404 的简单 Rest Web 服务

java - Jersey API + JPA/Hibernate Criteria 延迟加载不起作用

java - JAX-RS 如何从请求中获取 cookie?

java - Jersey REST 查询参数组合验证

java - Jackson:不同的 XML 和 JSON 格式

java - 我正在 weblogic 12.2.1.2 上部署一个restFull webservice webapp,但它失败了

java.lang.NoClassDefFoundError

c++ - Operator new 在有大量物理内存可用时抛出异常

c# - 在验证用于数字输入的文本框时,有没有办法避免抛出/捕获异常?

web-services - 从 POST Web 服务报告错误