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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Trending

  • SaaS in an Enterprise - An Implementation Roadmap
  • Creating a Web Project: Caching for Performance Optimization
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • Go 1.24+ Native FIPS Support for Easier Compliance
  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.

By 
Sanjay Patel user avatar
Sanjay Patel
DZone Core CORE ·
May. 27, 18 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
62.4K 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.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • RESTful Web Services: How To Create a Context Path for Spring Boot Application or Web Service
  • How To Validate HTTP Post Request Body - Restful Web Services With Spring Framework | Spring Boot
  • RESTful Web Services With Spring Boot: Reading HTTP POST Request Body

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!