Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling through spring AOP + Aspectj

In my project I have a domain layer which is basically POJO and a Spring controller / service layer that is sitting on top of the domain layer. I also have an AOP layer which is sitting between the service and domain.

My domain layer is throwing business exceptions which are now being handled in the service layer.

However I want to change it so that exception thrown from domain layer will be handled in the AOP layer. AOP layer will some kind of error response and send it back to spring controller/ web service layer.

I can create a IBizResponse and make two subclasses/interfaces of it perhaps a SuccessResponse and an ErrorResponse and make my domain layer methods return IBizResponse. However I am not able to figure out how to make AOP return the ErrorResponse object to the service layer.

like image 996
Nitish Raj Avatar asked Jul 17 '14 07:07

Nitish Raj


People also ask

How do I handle exceptions in Spring AOP?

After throwing is an advice type in Spring AOP. It ensures that an advice runs if a method throws an exception. We use @AfterThrowing annotation to implement the after throwing advice.

Which exception is thrown if an attempt is made to use a AspectJ?

AspectJ @AfterThrowing Annotation Usage AspectJ @AfterThrowing advice is executed after a join point does not complete normally and end up throwing an exception. @AfterThrowing ( "execution(* com.

Does Spring AOP use AspectJ?

In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (the @AspectJ style). Join point: a point during the execution of a program, such as the execution of a method or the handling of an exception.


1 Answers

See After throwing advice section of https://docs.spring.io/spring/docs/4.1.0.RELEASE/spring-framework-reference/htmlsingle/#aop-introduction-defn

After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using the @AfterThrowing annotation:

Examples

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;

@Aspect
public class AfterThrowingExample {

   @AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
   public void doRecoveryActions() {
     // ...
    }

}



import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;

@Aspect
public class AfterThrowingExample {

    @AfterThrowing(
    pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
    throwing="ex")
    public void doRecoveryActions(DataAccessException ex) {
       // ...
     }

}
like image 61
vinayknl Avatar answered Sep 30 '22 22:09

vinayknl