springspring-bootspring-aopaspect

Is it possible to throw checked exception in Spring AOP?


Hello I'm trying to throw custom Exceptions from my @Aspect, but no matter what exception I throw, my Aspect is throwing UndeclaredThrowableException,

My custom exception is

public class AuthorizationException extends RuntimeException {
    public AuthorizationException(String msg) {
        super(msg);
    }
}

And my Aspect is

@Around("@annotation(MyCustomAnnotation)")
    public Object validateAspect(ProceedingJoinPoint pjp throws Throwable {

    // for testing purpose directly throwing
    throw new AuthorizationException("My custom error);
}

And I'm supposed to get AuthorizationException but I'm getting UndeclaredThrowableException

I have tried directly throwing RuntimeError from the validateAspect method and changed throws Throwable to throws AuthorizationException but still same. Tried to catch it with Global Exception handler as well but the custom string message is always null.


Solution

  • Your aspect is throwing a checked exception which is not declared in the intercepted method or one of its callers along the call stack. Unfortunately, you did not even post a stack trace, which is not very helpful. An MCVE is also missing, so I can only answer the question as generically as you were asking it.

    Your claim that throwing a runtime exception makes an UndeclaredThrowableException appear is simply false, unless part of the application, e.g. another aspect or interceptor applied via dynamic proxies, catches that runtime exception and throws a checked exception instead. If you disagree, please prove your claim by editing your question and adding an MCVE or linking to one on GitHub.

    Please read this tutorial in order to better understand your own situation:

    https://www.baeldung.com/java-undeclaredthrowableexception