I'm using a JAX-RS ExceptionMapper to catch application exceptions and return custom output. The problem is that in the context of the mapper I don't know what type of output to return (e.g. HTML vs. JSON) if there is no Accept
header supplied by the user. Currently the code uses a terrible hack based on the UriInfo request path to determine what media type is chosen. Ideally the media type should be the same as the @Produces annotation on the method that threw the exception, but I haven't been able to find any way to get that annotation in the ExceptionMapper
.
Is this possible, or is there some other way to return a sensible media type?
Other answers:
This answer advises using httpHeaders.getMediaType(), which returns the media type of the incoming request or null if there is no request body, and so doesn't help for GET requests.
Here's an implementation based on peeskillet's answer below.