获取ExceptionMapper中抛出异常的方法的@Produces注解

Get @Produces annotation of method that threw Exception in ExceptionMapper

我在抛出异常的方法上使用了 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 注释,但我无法在 ExceptionMapper.[=15 中找到任何方法来获取该注释=]

这可能吗,或者有其他方法可以 return 一种合理的媒体类型吗?

其他答案:

This answer 建议使用 httpHeaders.getMediaType(),其中 return 是传入请求的媒体类型,如果没有请求主体则为 null,因此对GET 请求。

下面是基于 peeskillet 的回答的implementation

您可以将 ResourceInfo 注入映射器。在那里你可以得到被调用的 Method 和 class。您可以通过一些反思来检查注释。

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;
}