0

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.

Community
  • 1
  • 1
elhefe
  • 3,404
  • 3
  • 31
  • 45
  • Downvoting this question without explaining what's wrong with it is very unhelpful. I've read through the question several times looking for problems, but it seems fine to me. – elhefe Feb 16 '17 at 18:00

1 Answers1

2

You can inject ResourceInfo in to the mapper. There you can get the Method being invoked, and the class. You can check the annotation with some reflection.

Method method = resourceInfo.getResourceMethod();
Class cls = resourceInfo.getResourceClass();
String[] mediaTypes;
Produces produces = method.getAnnotation(Produces.class);
if (produces == null) {
    produces = cls.getAnnotation(Produces.class);
}
if (produces != null) {
    mediaTypes = produces.value();
} else {
    mediaType = defaultMediaTypes;
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720