Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Exception Handling in Spring Boot REST Web Services: A Real-World Pattern

DZone's Guide to

Exception Handling in Spring Boot REST Web Services: A Real-World Pattern

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

· Integration Zone ·
Free Resource

The new Gartner Critical Capabilities report explains how APIs and microservices enable digital leaders to deliver better B2B, open banking and mobile projects.

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:

@RestControllerAdvice
public class MyExceptionHandler {

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(AccessDeniedException.class)
    @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:

@RestControllerAdvice
public class MyExceptionHandler {

    @Autowired
    private ErrorResponseComposer errorResponseComposer;

    @RequestMapping(produces = "application/json")
    @ExceptionHandler(Throwable.class)
    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. This approach has some benefits, which  be evident later.

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 itself without touching the common library.

Looks like a good pattern? Except for one thing: a controller advice won’t handle exceptions in filters. So, in the next post, we’ll discuss how to address that, and also go deeper on how exactly to code all this. So, stay tuned!

The new Gartner Critical Capabilities for Full Lifecycle API Management report shows how CA Technologies helps digital leaders with their B2B, open banking, and mobile initiatives. Get your copy from CA Technologies.

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

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}