将元数据添加到Java throwable对象中

问题描述 投票:0回答:1

在我的应用程序中,我执行一些业务逻辑,例如,我有业务逻辑方法:

@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

    }
java spring exception spring-aop
1个回答
0
投票
在Spring AOP中,可以建议方法执行(连接点)-在方法开始之前,方法完成之后(有无异常)或前后(方法开始之前和方法完成之后)。这也意味着该方法内的逻辑不能在运行时更改,只能对方法执行的输入或结果进行操作。
© www.soinside.com 2019 - 2024. All rights reserved.