Logger clean up Using Spring AOP

喜夏-厌秋 提交于 2019-12-11 14:04:03

问题


We're trying to introduce generic logger in our application using Spring AOP for log statements which are under catch block.

Before AOP

try
{
\\Business Logic 
}
catch(Exception e){
\\some recovery mechanism that won't be generic across different layers
log.error();//These statements needs to be moved to generic logger
}

After going through Spring Docs,I have found this can be done using AfterThrowing advice. After throwing advice is Advice to be executed if a method exits by throwing an exception.

In order to do this We'll to change our existing exception handling code by re throwing Exception inside catch block something like this for AfterThrowing Advice to work.

After AOP:

try
{
\\Business Logic
}
catch(Exception e){
 \\some recovery mechanism that won't be generic across different layers
throw e;
}

AOP code:

@Aspect
@Sl4j
@Component
public class LoggingAdvice {
    @AfterThrowing(pointcut = "execution (* * com..*(..)", throwing = "e")
    public void myAfterThrowing(JoinPoint joinPoint, Exception e) {    
    log.error("Exception occured",e);
    }
}

Do you think is there any better solution than this rather than rethrowing Exception in catch block and propagating it upwards as per call hierarchy?

Note any raised or unchecked exceptions would be catched anyway by AfterThrowing Advice..All i want to do is perform logger clean up by removing log.error inside catch block and have it generic using AOP.


回答1:


As was discussed here, @AfterThrowing is nice for logging exceptions which are actually thrown.

Your case is quite special as you want to log exceptions which are being caught/handled. If you use full AspectJ instead of Spring AOP for this use case you can use a handler(*) pointcut as described with sample code in this answer. It would enable you to factor out your log statements from your catch blocks without the need to escalate (re-throw) exceptions which have already been properly handled, thus changing your logic and making it necessary to catch them somewhere else later.




回答2:


The better approach is to remove the catch blocks as you are going to use @AfterThrowing anyway. And implement whatever you want to implement on top that aspect execution.



来源:https://stackoverflow.com/questions/57039598/logger-clean-up-using-spring-aop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!