I am using @ControllerAdvice
annotation for defining exceptions at application level. Now the problem is I am having two @ControllerAdvice
classes, one for REST and one for the normal web app. When I define @ExceptionHandler
for Exception.class
in both, only the first one is considered. How do I separate both? Or how can I catch an Exception and determine from where it has occured? Is there a way or else do I need to use controller-specific exception handlers?
Asked
Active
Viewed 1,063 times
1

Bastian Voigt
- 5,311
- 6
- 47
- 65

Satya
- 1,239
- 2
- 11
- 15
2 Answers
0
I resolved this issue by creating a custom exceptions for my application and giving one exception handler method for each of them with @exception handler.
I also used aspects to make sure that every exception is converted to any of the custom exceptions.
@Aspect
@Component
public class ExceptionInterceptor {
@AfterThrowing(pointcut = "within(x.y.package..*)", throwing = "t")
public void toRuntimeException(Throwable t)
throws ApplicationException1, ApplicationException2,ApplicationException3 {
if (t instanceof ApplicationException1) {
throw (ApplicationException1) t;
} else if (t instanceof ApplicationException2) {
throw (ApplicationException2) t;
} else
throw (ApplicationException3) t;
}
}
These will transfer control to @controlleradvice.

Satya
- 1,239
- 2
- 11
- 15
-
Could you explain a little bit more what you are doing here? How does this transfer control to either one of your ControllerAdvice classes? – Bastian Voigt May 24 '17 at 09:31
-1
I noticed this have been left for a month or so, so it might be old. But this article may help http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/.
The section 3.5 is probably what you are looking for, a custom Exception Resolver.

Michael
- 1,241
- 1
- 13
- 25
-
Thank you for the answer but I solved it using aspects so that all the exceptions will be thrown to single place. – Satya Sep 10 '13 at 17:36
-
I think this does not explain how to do exception handling for both REST APIs and HTML pages in the same Spring App. -1 – Bastian Voigt May 24 '17 at 09:34