[Java] Spring AOP 에서 Custom Exception 사용하기

Spring AOP는 CglibAopProxy 클래스를 이용하여 동작합니다.

아래 코드와 같이 super.process() 를 try-catch로 처리하고 있고, Runtime Exception은 exception 을 그대로 던질 수 있기 때문에 Custom Exception은 Exception 클래스가 아니라 RuntimeException을 상속받아서 사용해야 합니다


@Override
@Nullable
public Object proceed() throws Throwable {
    try {
        return super.proceed();
    }
    catch (RuntimeException ex) {
        throw ex;
    }
    catch (Exception ex) {
        if (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||
                KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) {
            // Propagate original exception if declared on the target method
            // (with callers expecting it). Always propagate it for Kotlin code
            // since checked exceptions do not have to be explicitly declared there.
            throw ex;
        }
        else {
            // Checked exception thrown in the interceptor but not declared on the
            // target method signature -> apply an UndeclaredThrowableException,
            // aligned with standard JDK dynamic proxy behavior.
            throw new UndeclaredThrowableException(ex);
        }
    }
}

/images/images_jsj3282_post_eeb0e722-571b-424b-bf3f-c50b24465e8c_v2naj.png