Search code examples
exceptionaopaspectj

How to handle exception in service layer


Springboot provides @ControllerAdvice to handle exceptions in controllers.

But in service layer, there is no such annotations.

I've learned about spring-aop uses @AfterThrowing track exception, but @AfterThrowing cannot catch exceptions.

Another solution is to catch all exceptions with @Around, but it is kind of wastful to just log exceptions.

So, how to handle exceptions in service layer graceful?


Solution

  • The general idea is to let exceptions bubble up to controllers where they can be taken care of by components annotated with @ControllerAdvice or @RestControllerAdvice.

    In order to achieve this you have to throw unchecked exceptions in your application when needed, i.e. if business validations fail. This also means that you have to catch any checked exceptions that might be thrown by third party dependencies and re-throw them as unchecked exceptions in your application, i.e. the infamous IOException and dozens of its sub-variants.

    Apart from the above there's usually no need to handle exceptions in the @Service or the @Repository layer. There's rarely a reason to introduce aspects for any exception handling related logic either.