Spring controller exception handling locally and globally

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 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?

Upvotes: 0

Views: 955

Answers (2)

Pasupathi Rajamanickam
Pasupathi Rajamanickam

Reputation: 2052

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
    }
}

Upvotes: 0

Soheil Rahsaz
Soheil Rahsaz

Reputation: 781

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.

Upvotes: 1

Related Questions