Dropwizard自定义异常映射器无法正常工作

时间:2015-02-09 10:35:18

标签: exception-handling dropwizard

我对dropwizard异常处理有一些奇怪的问题。我编写的自定义异常映射器与此http://gary-rowe.com/agilestack/2012/10/23/how-to-implement-a-runtimeexceptionmapper-for-dropwizard/非常相似。对于状态400,我的代码是

   if (webAppException.getResponse().getStatus() == 400) {  
              return Response
                .status(Response.Status.BAD_REQUEST)
                .entity("Request sent to server is bad.")
                .build();
            }

在代码中,当我使用throw new WebApplicationException(400)时效果很好,mapper捕获异常并返回带有消息的响应,但是当我修改代码看起来像这样时

String msg=webAppException.getResponse().getEntity().toString();
              return Response
                .status(Response.Status.BAD_REQUEST)
                .entity("Request sent to server is bad."+msg)
                .build();

并在代码中使用类似 throw new WebApplicationException(Response.status(400).entity("hello!").build())之类的内容 它只返回“你好!”。 Mapper根本不会捕获此异常。它仅在我提供状态代码时才会捕获。我使用此链接http://thoughtspark.org/2013/02/25/dropwizard-and-jersey-exceptionmappers/中的说明删除了所有dropwizard映射器,但它仍然没有捕获此异常。这不是因为mapper中的上述修改,因为它根本不调用“toResponse”方法。所以,我的问题是为什么它表现得像这样。我可以这样离开它“足够好”,但我想知道为什么它不会工作,如果它适用于mapper会更好,所以我可以更容易地处理异常。 提前致谢

1 个答案:

答案 0 :(得分:0)

通过调试,我们发现此行为是通过org.glassfish.jersey.server.ServerRuntimemapException方法)完成的。

此方法先检查if (throwable instanceof WebApplicationException),然后再检查if (waeResponse.hasEntity()),在这种情况下,它只返回waeResponse而没有调用任何异常映射器。

因此,当您抛出一个带有实体的响应的 WebApplicationException 时,它将不会到达您的异常映射器。

相关问题