Exception Handling in Spring Boot and Spring MVC

Sitewide-10usd300x250 In a Spring MVC application, there would be multiple ways to handle an exception and send a sensible response to the client. This post 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 ErrorAttributes and/or BasicErrorController to customize the response the way we want.

So, to summarize, when developing a Spring Boot application, overriding ErrorAttributes and/or BasicErrorController seems like a better way to handle errors than coding ControllerAdvices. Spring Lemon 0.12 (coming soon) embraces this mechanism. To know how exactly it implements the exception handling mechanism, you can have a look at the classes in its exceptions package.

Let me know what you think!

Leave a Reply

Your email address will not be published. Required fields are marked *