代码之家  ›  专栏  ›  技术社区  ›  hal9000

使用ExceptionMapper记录客户端错误

  •  0
  • hal9000  · 技术社区  · 6 年前

    https://github.com/dropwizard/dropwizard/blob/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/LoggingExceptionMapper.java

    这个实现的问题是,即使它同时捕获4**和5**个错误,它也只记录5**个错误。

    我需要实现ExceptionMapper,这样LoggingExceptionMapper就不用了,我的CustomExceptionMapper同时记录客户端和服务器的错误。

    我想知道我的应用程序如何知道它需要使用CustomExceptionMapper而不是Dropwizard类?

    另外,将CLIENT\u ERROR添加到if条件中,以注销所有错误是否足够?

    @Override
    public Response toResponse(E exception) {
        // If we're dealing with a web exception, we can service certain types of request (like
        // redirection or server errors) better and also propagate properties of the inner response.
        if (exception instanceof WebApplicationException) {
            final Response response = ((WebApplicationException) exception).getResponse();
            Response.Status.Family family = response.getStatusInfo().getFamily();
            if (family.equals(Response.Status.Family.REDIRECTION)) {
                return response;
            }
            if (family.equals(Response.Status.Family.SERVER_ERROR) || family.equals(Response.Status.Family.CLIENT_ERROR) {
                logException(exception);
            }
    
            return Response.fromResponse(response)
                    .type(MediaType.APPLICATION_JSON_TYPE)
                    .entity(new ErrorMessage(response.getStatus(), exception.getLocalizedMessage()))
                    .build();
        }
    

    还是有更好的办法?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Aditya Abhas    6 年前

    JAX-RS spec 关于ExceptionMapper:

    实现必须使用其泛型类型最接近的提供程序

    我的应用程序如何知道它需要使用CustomExceptionMapper而不是Dropwizard类?

    您可以从应用程序中抛出自定义异常,并为该特定异常创建ExceptionMapper。

    将CLIENT\u ERROR添加到if条件,注销所有错误就足够了吗?

    是的,4xx和5xx系列具有所有错误响应。