javaexceptionjax-rsdropwizardexceptionmapper

Use ExceptionMapper to log CLIENT_ERRORs


I am working on an application which uses Dropwizard, which has this implementation of ExceptionMapper: https://github.com/dropwizard/dropwizard/blob/master/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/LoggingExceptionMapper.java

Problem with this implementation is that even though this catches both 4** and 5** errors, it only logs 5** errors.

I need to implement ExceptionMapper such that LoggingExceptionMapper is not used at all and my CustomExceptionMapper logs both CLIENT_ERRORs and SERVER_ERRORs.

I am wondering how would my application know that it needs to use CustomExceptionMapper instead of the Dropwizard class?

Also would it suffice to add CLIENT_ERROR to if condition, to log out all errors?

@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();
    }

Or would there be a better way to do this?


Solution

  • JAX-RS spec about ExceptionMapper:

    When choosing an exception mapping provider to map an exception, an implementation MUST use the provider whose generic type is the nearest superclass of the exception.

    How would my application know that it needs to use CustomExceptionMapper instead of the Dropwizard class?

    You can throw a custom exception from your application and create an ExceptionMapper for that specific exception.

    Would it suffice to add CLIENT_ERROR to if condition, to log out all errors?

    Yes, 4xx and 5xx family has all the error responses.