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

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

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

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • 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

Trending

  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • Debugging With Confidence in the Age of Observability-First Systems
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • Driving DevOps With Smart, Scalable Testing
  1. DZone
  2. Coding
  3. Frameworks
  4. Exception Handling in Spring Boot WebFlux Reactive REST Web Services

Exception Handling in Spring Boot WebFlux Reactive REST Web Services

Let's take a look at exception handling in Spring Boot WebFlux reactive REST web services.

By 
Sanjay Patel user avatar
Sanjay Patel
DZone Core CORE ·
Jul. 31, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
44.5K Views

Join the DZone community and get the full member experience.

Join For Free

This is a continuation of our series on exception handling and validation in Spring Boot REST APIs. In earlier posts, we discussed a robust pattern for exception handling and validation in Spring Boot and MVC REST Web Services. Please go through that first if you have not already. To summarize, we recommended coding an ErrorComposer to compose errors from exception objects, which could be used in a controller advice as well as a custom error controller. The controller advice would catch exceptions bubbling up from your controllers, whereas the error controller would be the ultimate weapon for handling exceptions raised at all levels, e.g. in filters.

However, in WebFlux, Spring Boot provides a WebExceptionHandler filter instead of the error controller. So, instead of providing your custom error controller and error attributes, you would need to provide a custom WebExceptionHandler and/or  ErrorAttributes. For more details, refer to Spring Boot documentation.

So, in our case, coding a custom ErrorAttributes bean and using our ErrorComposer in that would be a nice solution. Spring Boot will recognize that bean and use that in its WebExceptionHandler. We can code it by extending Spring Boot's  DefaultErrorAttributes. A simple version could look as below:

@Component
public class CustomErrorAttributes<T extends Throwable> extends DefaultErrorAttributes {

    @Autowired
    private ErrorResponseComposer<T> errorResponseComposer;

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request,
            boolean includeStackTrace) {

        Map<String, Object> errorAttributes = super.getErrorAttributes(request, includeStackTrace);     
        addErrorDetails(errorAttributes, request);
        return errorAttributes;
    }

    protected void addErrorDetails(
            Map<String, Object> errorAttributes, ServerRequest request) {

        Throwable ex = getError(request);

        errorAttributes.put("exception", ex.getClass().getSimpleName());

        errorResponseComposer.compose((T)ex).ifPresent(errorResponse -> {

            if (errorResponse.getMessage() != null)
                errorAttributes.put("message", errorResponse.getMessage());

            Integer status = errorResponse.getStatus();

            if (status != null) {
                errorAttributes.put("status", status);
                errorAttributes.put("error", errorResponse.getError());
            }

            if (errorResponse.getErrors() != null)
                errorAttributes.put("errors", errorResponse.getErrors());           
        });
    }
}

As you see, it extends Spring Boot's DefaultErrorAttributes and overrides the getErrorAttributes method, adding the attributes compiled by our ErrorComposer. For an exact implementation, look at Spring Lemon's LemonReactiveErrorAttributes class. If you haven’t heard of Spring Lemon, yo should give it a look. 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.

So, with this, you can handle all exceptions in a WebFlux REST API seamlessly!

Finally, instead of coding the ErrorComposer and the exception handlers yourself, you can just use spring-lemon-exceptions library. To do so, just include the following in your pom:

<dependencies>
    <dependency>
        <groupId>com.naturalprogrammer.spring-lemon</groupId>
        <artifactId>spring-lemon-exceptions</artifactId>
        <version>1.0.0.M6</version>
    </dependency>
</dependencies>

<repositories>
    <repository>
        <id>naturalprogrammer</id>
        <url>https://naturalprogrammer.github.io/mvn-repository</url>
    </repository>
</repositories>

For exact details, refer to the Spring Lemon project.

Spring Framework Spring Boot REST Web Protocols

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
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)
  • 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

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!