Exception Handling in Spring Boot REST Web Services: A Complete Blueprint

DZone 's Guide to

Exception Handling in Spring Boot REST Web Services: A Complete Blueprint

Learn how to use Spring Boot when developing real-world RESTful web services using the Spring framework and Spring Boot.

· Integration Zone ·
Free Resource

If an exception occurs when processing an HTTP request in your services, you should return a 4xx or 5xx response with a precise body. A naive way to do so would be to catch the exception in your controller or service and return an appropriate ResponseEntity manually. But Spring provides smarter techniques — as you’d expect — which are well explained in its blog. In this post, we’ll discuss a real-world pattern for handling exceptions elegantly by using a couple of those techniques.

For code examples, we’ll refer to Spring Lemon. If you haven’t heard of Spring Lemon, it’s a library encapsulating the sophisticated non-functional code and configuration that’s needed when developing real-world RESTful web services using the Spring framework and Spring Boot.

Using Controller Advice

Among the techniques Spring provides, using a global controller advice seems like a good one to handle all the exceptions at a central place. You can code a set of methods in a controller advice class, each handling one type of exception. See this, for example:

public class MyExceptionHandler {

    @RequestMapping(produces = "application/json")
    @ResponseStatus(value = 403)
    public ErrorResponse handleAuthorizationException(AccessDeniedException ex) {
        // build a response body out of ex, and return that
    ... more such methods, one per exception type

Another way to use a controller advice would be to have just a single method for handling all exception types and delegate building the response to another component. See this, for example:

public class MyExceptionHandler {

    private ErrorResponseComposer errorResponseComposer;

    @RequestMapping(produces = "application/json")
    public ResponseEntity<?> handleException(Throwable ex) {
        ErrorResponse errorResponse = errorResponseComposer.compose(ex);
        return new ResponseEntity<ErrorResponse>(errorResponse, errorResponse.getStatus());

The above delegates building the response to another class: the ErrorResponseComposer. Spring Lemon follows this pattern — see its DefaultExceptionHandlerControllerAdvice as an example, and Spring Framework Recipes For Real World Application Development book for a detailed discussion. This approach has some benefits, which'll be evident shortly.

Coding the ErrorResponseComposer

So, the compose method of the ErrorResponseComposer should build the error response, given the exception. How do we code that?

You could have a bunch of if statements — one for each type of exception — but that’d be bad. You can’t handle a new exception type without altering this class, which could eventually go to a common library in a microservices architecture.

A good pattern instead would be to inject into the ErrorResponseComposer a collection of handlers, one for each exception type. Specifically, you can:

  1. Define individual exception handler components, one for each exception type you’d like to handle.
  2. Inject all those in the ErrorResponseComposer as a map.
  3. Refer that map in the compose method to find out the exact handler for the given exception type.

Later, in some microservice, if you introduce a new exception type, you can code its handler there, without touching the common library.

In the next post, we'll discuss how exactly to code all this. We'll also discuss how to handle errors at filter level, which controller advices won't. So, let's resume in the next post.

exception handling ,integration ,rest ,spring boot ,spring lemon ,tutorial ,web services

Published at DZone with permission of Sanjay Patel . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}