In our last post, we concluded that overriding
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:
- 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
- putErrorDetails(Map<String, Object> errorAttributes, T ex) – should fill the given
errorAttributesmap with the desired error response, by referring to the
exparameter (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
getStatusmethod 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.
Share your views!