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.
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.