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 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 DefaultErrorAttributes and/or BasicErrorController seems like a better way to handle errors than coding ControllerAdvices. In fact, Spring Lemon 0.12 embraces this mechanism.

Let me know what you think! In the next post, we’ll go deeper – looking at how exactly to layout an elegant exception handling mechanism, taking Spring Lemon as an example.

Leave a Reply

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