【问题标题】:JAVA aop @AfterThrowing couldn't catch ExceptionJAVA aop @AfterThrowing 无法捕获异常
【发布时间】:2021-08-18 08:57:16
【问题描述】:

当此方法出现异常时,我想执行一些操作。 所以我做了一个类似AfterReturning、AfterThrowing的aop函数……

我故意更改了引发异常的方法。 但是请求到达AfterReturning,而不是AfterThrowing,即使发生异常。

如何让这个请求到达 AfterThrowing 方法?

    @EventListener
    @GetHost
    public void getHost(ContextRefreshedEvent event) throws Exception {

        try {
            prHostName = InetAddress.getLocalHost().getHostName();
            prIpAddr = InetAddress.getLocalHost().getHostAddress();

            //making exception on purpose
            String[] tmp = new String[0];
            prIpAddr = tmp[1];


        } catch (Exception exception) {
            prHostName = "unknown";
            prIpAddr = "unknown";
            System.out.println("unknown");
            exception.printStackTrace();

        }
    }

有aop方法

    @Pointcut("@annotation(com.etc.web.annotation.GetHost)")
    public void componentMethod() {}

    @Before("componentMethod()")
    public void beforeComponent(JoinPoint point) {
        System.out.println("beforeComponent");

    }

    @Around("componentMethod()")
    public Object aroundComponent(ProceedingJoinPoint point) throws Throwable {

        System.out.println("aroundComponent");
        Object retVal = point.proceed();

        return retVal;
    }
    @AfterReturning(pointcut = "componentMethod()", returning = "result")
    public void afterComponent(JoinPoint point, Object result) {
        System.out.println("afterReturnComponent");

    }

    @AfterThrowing(pointcut = "componentMethod()", throwing = "exception")
    public void afterThrowingComponent(JoinPoint point, Throwable exception) throws Exception {
        System.out.println("afterThrowingComponent");

       
    }

请帮助我。 谢谢!

【问题讨论】:

    标签: java exception aop


    【解决方案1】:

    方法没有异常退出,因为异常被捕获,方法正常退出。所以当然不会触发@AfterThrowing。这应该不会让您感到惊讶。

    【讨论】:

    • 谢谢kriegaex!那么如果我删除 catch 表达式,@AfterThrowing 会被触发吗?
    • 是的,Julia,如果没有其他错误或配置问题,那就应该发生。
    猜你喜欢
    • 2021-05-19
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    相关资源
    最近更新 更多