Обработка исключений Aspectj для нескольких советов - PullRequest
0 голосов
/ 30 октября 2019

У меня есть 2 аспекта, которые применяются к одному и тому же методу. Когда метод выполняется правильно, у меня нет проблем, все работает нормально, и оба аспекта работают как положено. Проблема в том, что метод вызывает исключение. В этих случаях первый аспект корректно перебрасывает исключение, но второй аспект генерирует нулевое исключение. Мне удалось воспроизвести проблему, изолировав кейс на модульном тесте в отдельном проекте. Это аспекты (на самом деле я удалил всю логику, на данный момент они ничего не делают):

@Aspect
public class LogContextConstantAspect {

    @Around("execution(* *(..)) && @annotation(logContextConstant)")
    public Object aroundMethod(ProceedingJoinPoint joinPoint, LogContextConstant logContextConstant) throws Throwable {
        try {
            Object res = joinPoint.proceed();
            return res;
        } catch (Throwable e) {
            throw e;
        }
    }
}

и

@Aspect
public class LogExecutionTimeAspect {

    @Around("execution(* *(..)) && @annotation(logExecutionTime)")
    public Object around(ProceedingJoinPoint joinPoint, LogExecutionTime logExecutionTime) throws Throwable {
        try {
            Object res = joinPoint.proceed();
            return res;
        } catch (Throwable e) {
            throw e;
        }
    }
}

, в то время как это две пользовательские аннотации, которые я реализовал

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {

    String paramKey() default "execution_time";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Documented
public @interface LogContextConstant {

    String name();

    String value();
}

затем я создал простой класс со следующими методами

public class AspectSimple {

    public int execute() {
        System.out.println("ok");
        return 1;
    }

    public int failSimple() throws CustomException {
        throw new CustomException("ko");
    }

    @LogExecutionTime
    public int failWithAspect1() throws CustomException {
        throw new CustomException("ko");
    }   

    @LogContextConstant(name="test", value = "test")
    public int failWithAspect2() throws CustomException {
        throw new CustomException("ko");
    }   


    @LogExecutionTime
    @LogContextConstant(name="test", value = "test")
    public int executeWithAspect() {
        return 1;
    }

    @LogExecutionTime
    @LogContextConstant(name="test", value = "test")
    public int failWithAspect3() throws CustomException {
        throw new CustomException("ko");
    }   
}

и, наконец, этот модульный тест

public class TestSample {

    static AspectSimple as = null;

    @BeforeAll
    public static void setup() {
        as = new AspectSimple();
    }

    @Test
    public void test1() {
        int res = as.execute();
        assertEquals(1, res);
    }

    @Test
    public void test2() {
        int res = as.executeWithAspect();
        assertEquals(1, res);
    }

    @Test
    public void test3() {
        try {
            int res = as.failSimple();
        } catch (CustomException e) {
            assertNotNull(e); 
        } catch (Exception e) {
            fail();
        }
    }   

    @Test
    public void test4() {
        try {
            int res = as.failWithAspect1();
        } catch (CustomException e) {
            assertNotNull(e); 
        } catch (Exception e) {
            fail();
        }
    }       

    @Test
    public void test5() {
        try {
            int res = as.failWithAspect2();
        } catch (CustomException e) {
            assertNotNull(e); 
        } catch (Exception e) {
            fail();
        }
    }       

    @Test
    public void test6() {
        try {
            int res = as.failWithAspect3();
        } catch (CustomException e) {
            assertNotNull(e); 
        } catch (Exception e) {
            fail();
        }
    }       

}

Все тесты работают правильно,отказывает только последний (test6).

приложение работает на Java 8, с aspectj 1.9.4 и junit 5. Здесь полный pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>it.pivimarco.samples.aspects</groupId>
    <artifactId>aspect-sample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <version>1.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-engine</artifactId>
            <version>1.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-commons</artifactId>
            <version>1.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <version>5.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-params</artifactId>
            <version>5.5.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjtools</artifactId>
            <version>1.9.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>
                                        org.baeldung.executable.ExecutableMavenJar
                                    </mainClass>
                                </manifest>
                            </archive>
                            <descriptorRefs>
                                <descriptorRef>jar-with-dependencies</descriptorRef>
                            </descriptorRefs>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.0</version>
                <executions>
                    <execution>
                        <id>default-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>test</goal>
                        </goals>
                        <configuration>
                            <includes>
                                <include>**/Test*.java</include>
                                <include>**/*Test.java</include>
                                <include>**/*Tests.java</include>
                                <include>**/*TestCase.java</include>
                            </includes>
                            <properties>
                                <excludeTags>slow</excludeTags>
                            </properties>
                            <forkCount>1</forkCount>
                            <reuseForks>false</reuseForks>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <includes>
                        <include>**/Test*.java</include>
                        <include>**/*Test.java</include>
                        <include>**/*Tests.java</include>
                        <include>**/*TestCase.java</include>
                    </includes>
                    <properties>
                        <excludeTags>slow</excludeTags>
                    </properties>
                    <forkCount>1</forkCount>
                    <reuseForks>false</reuseForks>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <target>1.8</target>
                    <source>1.8</source>
                    <parameters>true</parameters>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>1.11</version>
                <dependencies>
                    <dependency>
                        <groupId>org.aspectj</groupId>
                        <artifactId>aspectjtools</artifactId>
                        <version>1.9.4</version>
                        <scope>compile</scope>
                    </dependency>
                </dependencies>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <proc>none</proc>
                    <complianceLevel>1.8</complianceLevel>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Если яПримените только один аспект, исключение CustomException выбрасывается в соответствии с требованиями, но когда оба аспекта применяются, я получаю nullpointerexception.

Я также попытался объявить приоритетность аспектов, используя аннотацию DeclarePrecedence, но этоне работал

@DeclarePrecedence("it.pivimarco.samples.aspects.LogContextConstantAspect,it.pivimarco.samples.aspects.LogExecutionTimeAspect")

Это трассировка стека NPE

java.lang.NullPointerException
    at it.pivimarco.samples.aspects.AspectSimple.failWithAspect3_aroundBody10(AspectSimple.java:35)
    at it.pivimarco.samples.aspects.AspectSimple$AjcClosure11.run(AspectSimple.java:1)
    at org.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:170)
    at it.pivimarco.samples.aspects.LogContextConstantAspect.aroundMethod(LogContextConstantAspect.java:18)
    at it.pivimarco.samples.aspects.AspectSimple.failWithAspect3(AspectSimple.java:35)
    at it.pivimarco.samples.aspects.TestSample.test6(TestSample.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

1 Ответ

0 голосов
/ 05 ноября 2019

Я думаю, что вы обнаружили ошибку в компиляторе AspectJ (версии 1.9.3, 1.9.4), которая отсутствует в версии 1.9.2, как я сказал в своем комментарии. Я только что создал AspectJ сообщение об ошибке # 552687 от вашего имени. Пожалуйста, проверьте там для дальнейших обновлений. Сейчас вы можете просто перейти на 1.9.2 и продолжить работу.

...