0

I am using Jersey in Spring Boot. I have a ExceptionMapper<Throwable> registered via ResourceConfig.register(MyExceptionMapper.class) and it is annotated with @Provider.

If my code throws a RuntimeException MyExceptionMapper.toResponse() DOES get called.

However, if my application throws a javax.ws.rs.ForbiddenException, then my ExceptionMapper is not called even though it is a ExceptionMapper<Throwable>.

I am assuming that Jersey has a default ExceptionMapper that is handing WebApplicationException (I assume). How can I customize this?

All I really want to do is add DEBUG logging in the case of any Throwable (rest of code works fine for non-WebApplicationException). Is there a better way to do this?

John B
  • 32,493
  • 6
  • 77
  • 98

1 Answers1

0

So two parts:

First, the reason Jersey is not hitting my ExceptionMapper is that it only tries to do so if it does not internally support mapping. The ServerRuntime.Responder class attempts to map any WebApplicationException. Only if this does not succeed for any reason will the exception be provided to the ExceptionMapper (at least that is the behavior I has seen).

Second, there are a couple ways to add logging:

  • set the logging level for the ServerRuntime.Responder. For me this is too broad as it would log all responses and not just exceptions. This is described here: https://stackoverflow.com/a/41484564/905762
  • The solution I went with was to add a ContainerResponseFilter and get the exception from the ContainerRequest. This is somewhat described here: https://stackoverflow.com/a/19680862/905762

    public class ExceptionsLoggingContainerResponseFilter implements ContainerResponseFilter { private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionsLoggingContainerResponseFilter.class);

    @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { Throwable throwable = ((ContainerRequest)response).getMappedThrowable(); if (throwable != null) { LOGGER.info(buildErrorMessage(request), throwable); } }

John B
  • 32,493
  • 6
  • 77
  • 98