简体   繁体   中英

log the exception in spring using aspectJ?

Please don't hesitate to edit the question or to ask more details about the questin.

I know I can log the ArithmeticException of the below method using the aspectJ as,

public void afterThrowingAspect(){
    System.out.println("This is afterThrowingAspect() !");      
    int i=2/0;
    System.out.println("i value : "+i);
}

The AspectJ class has,

@AfterThrowing(pointcut = "execution(* com.pointel.aop.test1.AopTest.afterThrowingAspect(..))",throwing= "error")
public void logAfterError(JoinPoint joinPoint,Throwable error) {
    System.out.println("Hi jacked Method name : " + joinPoint.getSignature().getName());
    log.info("Method name : " + joinPoint.getSignature().getName());
    log.info("Error report is : " + error);

}

Normally I can handle exception using the TRY and CATCH block and log the errors in the every CATCH block as ,

public void someMehtod(){
    try{        
        int i=2/0;
        System.out.println("i value : "+i);
    }catch{ArithmeticException err){
        log.info("The exception you got is : " + err);
    }
}

But I don't like to do the logging like with every single catch block individually in all the java classes of my project like ,

log.info("The exception you got is : " + err); 

I would like to do the logging inside CATCH block in my application using the aspectJ class.

Hope you are all understand my question.Thanks.

Its possible to simply remove the try/catch from your code and simply log the exception in your aspect.

public void someMehtod(){
        int i=2/0;
        System.out.println("i value : "+i);
}

Because you don't re-throw the exception in the aspect then it won't bubble up. Although this is possible I strongly advise you to think more about what you are trying to do here. Why do you need to log the fact that an exception has been thrown? Exceptions aren't necessarily only for errors but can occur in normal code journeys. Simply logging only the exception name is unlikely to help you debug the problem. Therefore, you will probably want a bespoke log message for each catch block. If you do find repetition you could create a method to log out the result.

Hope this helps,

Mark

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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