0

I would like some advice on how to achieve the following. I'm not providing code, as my problem is theoretical, but upon request I can. So this is the situation:

  • I have multiple controllers, each can throw XYException
  • I have a @ControllerAdvice class, in which I have an @ExceptionHandler watching for XYExceptions. When it happens, it prints out "XY".
  • In one (and only one) controller, when XYException is thrown, I want to do some additional task (let's say, do something that only that controller can do), and then I want the exception to be "passed on" to the global handler mentioned above.

I know I can catch the exception, do the desired task in catch block, and then re-throw the exception so the global handler can catch it, but what if I have 23 methods in the controller potentially throwing XYExceptions, and I do not want to put try-catch blocks in all 23 methods.

What is the clean Spring way of achieving this?

2 Answers2

1

You could use AOP to achieve that. You'd write a method that intercepts the method inside that controller and when they throw an exception, you're aop method would run and you can do your stuff and then the exception would go in your handler class.

To achieve that you should have a class and anotate it with @Aspect and @Component then have a method anotated with @AfterThrowing and setting the pointcut which will intercept when the given method throws an exception.

Look into Aspect Oriented Programming and Aspectj for more info.

Soheil Rahsaz
  • 719
  • 7
  • 22
  • Thanks, I know AOP, but I've never actually used it. I did look into it, and it seems that it will solve my problem. Funny thing however, that on the very day I posted this (and read your response), I could not make it work. I left the project for three weeks, came back today, and now it seems working (only logging though, but that means it's working). – Málnás Péter Oct 11 '19 at 09:13
0

The easy way to handle this case in ControllerAdvice is checking the stacktrace where the exception originated.

@ExceptionHandler(Exception.class)
public String handleExc(HttpServletRequest req, HttpServletResponse res, Exception e) {
    if ( /*Have all null and safe check */ e.getStackTrace()[0].contains("MyController")) {
        // Do your exception handling
    }
}
Pasupathi Rajamanickam
  • 1,982
  • 1
  • 24
  • 48