Exception handling in Spring Boot and Spring MVC – Part II

Sitewide-10usd300x250 In our last post, we concluded that overriding DefaultErrorAttributes and BasicErrorController would be a good way to handle exceptions in a Spring Boot application. But, how exactly to layout a clean exception handling mechanism?

As an example, in this post, let’s have a look at how Spring Lemon does it.

First, have a look at the getErrorAttributes method of Spring Boot’s DefaultErrorAttributes. It’s the one that’d return the body of the error response (as a map, which is eventually converted to JSON).

Spring Lemon’s LemonErrorAttributes overrides it, and delegates rendering the response body to individual beans of type LemonExceptionHandler. So, for handling a certain type of exception, you’ll need to provide a corresponding bean implementing LemonExceptionHandler. Specifically, LemonExceptionHandler has two methods that you’ll need to implement:

  1. getExceptionName() – should return the simple name of the exception class. For example, if you’re coding a handler for javax.validation.ConstraintViolationException, it should return "ConstraintViolationException".
  2. putErrorDetails(Map<String, Object> errorAttributes, T ex) – should fill the given errorAttributes map with the desired error response, by referring to the ex parameter (the caught exception object). In errorAttributes, you can also put an HttpStatus with key "httpStatus", which’ll be the HTTP status code of the response. If you don’t put it, the getStatus method of Spring Boot’s BasicErrorController would be used for getting the HTTP status.

To make your job easy, Spring Lemon provides AbstractExceptionHandler and AbstractBadRequestExceptionHandler that your exception handlers may choose to extend. In fact, Spring Lemon comes with a few pre-coded handlers (look at the beans in the handlers package). They are beans annotated with @Order(Ordered.LOWEST_PRECEDENCE), so that, if you provide another handler handling the same exception, yours’ll take precedence.

To get a detailed idea, have a look at the classes in the exceptions package, and the handlers package inside that.

Share your views!

Leave a Reply

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