简体   繁体   English

JAVA aop @AfterThrowing 无法捕获异常

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

I want to do some action when this method has an exception.当此方法出现异常时,我想执行一些操作。 Therefore I made aop function like AfterReturning, AfterThrowing...因此我做了aop function 像AfterReturning,AfterThrowing ...

I changed the method raising exception on purpose.我故意更改了引发异常的方法。 But the request arrives AfterReturning, not AfterThrowing even if exception is occured.但是请求到达AfterReturning,而不是AfterThrowing,即使发生异常。

How can I make this request reach to AfterThrowing method?我怎样才能使这个请求到达 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();

        }
    }

There are aop methods有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");

       
    }

Please help me.请帮我。 Thanks!谢谢!

The method does not exit with an exception, because the exception is caught and the method exits normally.该方法不会因异常而退出,因为异常被捕获并且该方法正常退出。 So of course, @AfterThrowing is not triggered.所以当然, @AfterThrowing不会被触发。 That should not surprise you.这不应该让你感到惊讶。

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

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