Write an exception in spring using aspectJ?

Please feel free to edit the question or ask more detailed information about the quest.

I know that I can log ArithmeticException method below using 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); } 

Usually I can handle the exception using TRY and CATCH blocks and log errors in each CATCH block, like,

 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 doing logging as with every single CATCH block separately in all java classes of my project, for example,

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

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

Hope you all understand my question. Thanks.

+4
source share
1 answer

It can simply be removed by try / catch from your code and just registered an exception in your aspect.

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

Since you are not throwing an exception into an aspect, then it will not bubble. Although this is possible, I highly recommend that you think more about what you are trying to do here. Why do you need to register the fact that an exception is thrown? Exceptions are not necessary only for errors, but can occur on regular trips with a code. Just logging just an exception is unlikely to help you debug the problem. So you probably want to order a log message for each catch block. If you find repetition, you can create a method to exit the result.

Hope this helps,

Mark

0
source

Source: https://habr.com/ru/post/1499316/


All Articles