In a Spring MVC application, there would be multiple ways to handle an exception and send a sensible response to the client. This post at Spring Blog explains some of those beautifully. Among those, using a global ControllerAdvice seems most sensible when developing a REST API. In fact, Spring Lemon 0.11 uses that approach.
However, ControllerAdvices can’t handle exceptions thrown at filter levels – e.g. exceptions thrown from Spring Security filters.
How to handle those?
We can exploit Servlet’s exception handling mechanism in such cases. In other words, we can tell the servlet container to render an “error” page when an exception occurs. In fact, Spring Boot already uses this mechanism and provides a BasicErrorController mapped to
/error. When an exception is thrown, the /error page is rendered. You can find more details about it in Spring Boot documentation. As stated there, we can override DefaultErrorAttributes and/or BasicErrorController to customize the response the way we want.
So, to summarize, when developing a Spring Boot application, overriding
BasicErrorController seems like a better way to handle errors than coding
ControllerAdvices. In fact, Spring Lemon 0.12 embraces this mechanism.