【发布时间】:2020-08-12 10:51:18
【问题描述】:
在我的应用程序中,我执行一些业务逻辑,例如我有业务逻辑方法:
@Override
@ByPassable(exceptions = {"InvalidIdentityException"})
public void validate(Model model) {
if (nonNull(model)) {
final boolean test = isOk(model.getIdentity());
if (test) {
throw new InvalidIdentityException("Invalid bla bla");
}
}
}
以及自定义异常类:
public class InvalidIdentityException extends SomeException {
public InvalidIdentityException (final String message) {
super(message);
}
}
方法上的@ByPassable 获取可以绕过的异常列表,因此在这种情况下会抛出InvalidIdentityException,并且在不久的将来重新执行此方法时它会变为bypassable。
我为我的 Spring Boot 应用程序启动了一个具有一组可绕过异常的 bean:
public class Config {
@Bean("bypassable-exceptions")
public Set<String> getBypassableExceptions() {
final Set<String> exceptions = new HashSet<>();
new Reflections(new MethodAnnotationsScanner())
.getMethodsAnnotatedWith(ByPassable.class).stream()
.filter(method -> method.getAnnotation(ByPassable.class).enabled())
.forEach(method -> {
final String[] exceptions = method.getAnnotation(ByPassable.class).exceptions();
exceptions.addAll(Arrays.asList(exceptions));
});
return exceptions;
}
}
每当在方法中抛出 Bypassable 异常时,我的应用程序都会将 Throwable 对象作为 Json 保存在数据库中,但是我需要在该可抛出对象上添加一个额外的布尔属性 bypassable将@BeforeThrowing 异常更新为拦截。这可能吗?
public class ExceptionAspect {
@Pointcut("@annotation(com.services.aop.ByPassable)")
public void byPassableExceptionMethods() {
}
@BeforeThrowing(pointcut = "byPassableExceptionMethods()", throwing = "exception")
public void beforeThrowingAdviceForByPassableExceptionMethods(final JoinPoint jp,
final Throwable exception) {
// check against the set of bypassable exceptions and update a custom property on the exception
class so when Throwable is persisted it is persisted with this customer property e.g. bypassable
= true
}
【问题讨论】:
-
if (test)为true时是否需要拦截并设置属性?此属性不是 Exception 构造函数的一部分的任何具体原因? -
要求是拦截在抛出可绕过异常的方法上抛出的异常,并在 Exception 类上添加标志以表明它是可绕过的
-
@AfterThrowing是建议类型,我相信你已经经历过了。如果要求在方法抛出异常时提供建议,@AfterThrowing将捕获该异常。@BeforeThrowing的用法有点混乱,因为我无法理解这里的确切要求
标签: java spring exception spring-aop