1

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?

buzz
  • 11
  • 1
  • Welcome to SO. You are somewhat contradicting yourself here: Either you just want to log exceptions, then `@AfterThrowing` is fine. Or you want to catch and handle exceptions, then you need `@Around`. Maybe I do not understand your problem, because you are not playing by the rules, asking questions about concrete code, which ideally should be an [MCVE](https://stackoverflow.com/help/mcve) (please do read that article). – kriegaex Oct 08 '22 at 08:28

1 Answers1

3

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.

Attila T
  • 577
  • 1
  • 4
  • 18