我找了很多东西,但找不到任何有用的东西。
问题:我已经创建了自定义注释,如:
@MapExceptions(value = {
@MapException(sources = {IllegalArgumentException.class, RuntimeException.class}, destination = BadRequestException.class),
@MapException(sources = {RuntimeException.class}, destination = BadRequestException.class)
})我用Guice做DI。
公共类MapExceptionInterceptor实现MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
try {
return invocation.proceed();
} catch (Exception actualException) {
Method method = invocation.getMethod();
Annotation[] annotations = method.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MapException) {
MapException mapException = (MapException) annotation;
Class<? extends Throwable> destinationClass = mapException.destination();
Class<? extends Throwable>[] sourceClasses = mapException.sources();
for (Class sourceExceptionClass : sourceClasses) {
if (actualException.getClass().isInstance(sourceExceptionClass)) {
Constructor ctr = destinationClass.getConstructor(String.class);
throw (Throwable) ctr.newInstance(actualException.getMessage());
}
}
}
}
throw actualException;
}
}}
我正在使用下面的绑定
bindInterceptor(Matchers.any(), Matchers.annotatedWith(MapException.class), new MapExceptionInterceptor());这样可以吗?还是我可以改进?
谢谢!
发布于 2016-03-27 09:45:17
因此,内部注释只是一个数据包。为了解决这个问题,我为外部注释(MapExceptions)编写了拦截器,它完成了所有工作。
https://stackoverflow.com/questions/36130777
复制相似问题