Spring WebFlux Rest API Global exception handling
The purpose of this story is to explain how to implement custom exception handling with Spring WebFlux for a REST API.
Error handling is one of the ways we make sure we handle our failures consistently. The benefit of handling exceptions globally is that we can customize all error output from our API into a single format that all consumers can understand. This will guarantee us easier and faster maintenance.
This is the list of all the prerequisites for following this story:
- Java 17
- Spring Boot / Starter WebFlux 2.6.7
- Lombok 1.18
- Maven 3.6.3
UnAuthorizedException.java: This is a user-defined class extending the java.lang.RuntimeException class.
When we test the
http://localhost:8080/api/book endpoint, it will throw a default internal error exception.
Global Error Handling
The custom exception system provided in
SpringMVC doesn’t work in
Spring-WebFlux for the simple reason that the underlying runtime containers are not the same.
WebExceptionHandler is the top-level interface to the exception handler of
Spring-WebFlux, so it can be traced back to the subclass.
Spring Boot provides a
WebExceptionHandler that sensibly handles all errors. Its position in the processing order is immediately before the handlers provided by WebFlux, which are considered last.
We need two steps to create our custom exception:
- Customize the Global Error Response Attributes
- Implement the Global Error Handler
The first step in customizing is to override the getErrorAttributes method of the parent default error attribute class DefaultErrorAttributes to get the error attribute and catch the corresponding exception from the service request encapsulation ServerRequest.
Here we defined a standard error JSON response with code, message, and timestamp. exceptionsRules is an ExceptionRule record list that contains all user-defined exception classes with the desired error status.
Now, let’s implement the Global Error Handler.
This class extends the AbstractErrorWebExceptionHandler class provided by the spring and custom implements the handling of the Global Exception. @Order(-2) is used to give a priority boost to the component that the Spring Boot class DefaultErrorWebExceptionHandler which is of Order(-1) priority.
Run the application and test the API using POSTMAN.
It can be seen from the figures above that the received JSON response is uniform for all detected errors.
Well done !!. In this story, We have seen the customized exception handling using Spring Webflux.
The complete source code is available on GitHub.