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

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

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

  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • Designing AI Multi-Agent Systems in Java
  • Evaluating the Evaluators: Building Reliable LLM-as-a-Judge Systems
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  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

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
  • [email protected]

Let's be friends: