DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Frameworks
  4. Exception Handling in Spring Boot REST Web Services: A Complete Blueprint

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.

Sanjay Patel user avatar by
Sanjay Patel
CORE ·
May. 27, 18 · Tutorial
Like (10)
Save
Tweet
Share
61.10K Views

Join the DZone community and get the full member experience.

Join For Free

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, 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.

Spring Framework REST Web Protocols Web Service microservice Spring Boot

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using JSON Web Encryption (JWE)
  • Beginners’ Guide to Run a Linux Server Securely
  • Java Development Trends 2023
  • Why Every Fintech Company Needs DevOps

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: