Brian
Brian

Reputation: 13571

Spring annotations: Is there a similar annotation like @ExceptionHandler used in Controller stereotypes for @Repository or @Service stereotypes?

I tried to see if I could use org.springframework.web.bind.annotation.ExceptionHandler in a Repository out of curiosity. As expected the annotation is ignored.

I have a low priority instrumentation service that I don't want exceptions to bubble up from. Rather than coding each method on the instrumentation service with a try/catch I would have liked to have a @ExceptionHandler method for the service - similar to technicques used in a Spring @Controller.

Thoughts?

Upvotes: 2

Views: 349

Answers (1)

nicholas.hauschild
nicholas.hauschild

Reputation: 42849

I do not think that you can get this from Spring right now (perhaps you want to make a feature request...), but you should be able to do this pretty easily with Spring AOP.

@Aspect
public class DaoAspect {
    @AfterThrowing(/*any method in a @Repository class that is not annotated with @ExceptionHandler*/ throwing="ex")
    public void doRecoveryActions(DataAccessException ex) {
        //find method of throwing class that can handle the exception via @ExceptionHandler
    }
}

Upvotes: 1

Related Questions