繁体   English   中英

JAVA aop @AfterThrowing 无法捕获异常

[英]JAVA aop @AfterThrowing couldn't catch Exception

当此方法出现异常时,我想执行一些操作。 因此我做了aop function 像AfterReturning,AfterThrowing ...

我故意更改了引发异常的方法。 但是请求到达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");

       
    }

请帮我。 谢谢!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM