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.
AfterThrowing
work and catch exception again in generic AOP code to log it. – Sagar Kadu@AfterThrowing
doesn't depend on a catch block. – M. Deinum@AfterThrowing
doesn't depend on a catch block but I want my method to exit withException
for@AfterThrowing
to work so that i can log the stacktrace in AOP code rather than logging it in Business logic – Sagar Kaduthrow e
when doing acatch (Exception e)
help? It is exactly the same if you leave out the catch... Unless you want to convert to a specialized exception and throw that (but that isn't what is clear in the question). Also if you convert why not make the conversion generic and do the logging there instead of using AOP. ( – M. Deinum