问题特定类的异常处理/映射 https://stackoverflow.com/questions/36370991让我想到了如何注册的问题ExceptionMapper
到特定资源Method.
我尝试过使用DynamicFeature
像这样:
动态特征
@Provider
public class ExceptionMapperDynamicFeature implements DynamicFeature {
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
if(!resourceInfo.getResourceMethod().isAnnotationPresent(BindExceptionMapper.class))
return;
BindExceptionMapper bem = resourceInfo.getResourceMethod().getAnnotation(BindExceptionMapper.class);
context.register(bem.mapper());
}
}
注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface BindExceptionMapper {
Class<? extends ExceptionMapper<?>> mapper() default WebApplicationExceptionMapper.class;
}
Resource
@GET
@Produces(MediaType.APPLICATION_JSON)
@BindExceptionMapper
public Response test() {
// do something that throws an exception
}
结果却让人大失所望:
警告:类 ...WebApplicationExceptionMapper 提供程序的给定协定(接口 javax.ws.rs.ext.ExceptionMapper)无法绑定到资源方法。
然后我寻找其他可能性,但没有运气,最终得到了 AspectJ 实现,你可以将其视为我的回答的一部分 https://stackoverflow.com/questions/36370991/exception-handling-mapping-for-a-particular-class/36374188#36374188到上面链接的问题。
所以完整的问题:
有没有办法成功地将 ExceptionMapper 注册到资源方法?
而且当然,
我很好奇答案:)
请注意:
这个问题不是要注册ExceptionMapper
到资源Class like...
public class ApplicationResourceConfig extends ResourceConfig {
public ApplicationResourceConfig() {
register(WebApplicationExceptionMapper.class, TestResource.class);
}
}
尤其是根本不打算注册它们。