Exception Handling in Spring webflux
In this tutorial we will learn How to handle Exception for functional endpoint in spring webflux.
To do this only we need to add only two classes in already created project. After that any exception that our handler function throws will be automatically translated to an Http status and a JSON error body will be get in response.
These two classes already available 1. DefaultErrorAttributes and 2. AbstractErrorWebExceptionHandler. So we can override these classes in our project according to our requirement.

To customize error attributes that we are getting in API response. We can customize these attributes, To customize these we can simply extend the DefaultErrorAttributes class and override its getErrorAttributes(-,-) method.

Here, we want to return error message that we are getting from exception, API path and error value Bad Request as part of the Error Attributes when an exception occurs.
Next Lets implement the Global Exception Handler. For this spring provides a convenient AbstractErrorWebExceptionHandler class for us to extend and implement in handling global exception.

Here we are overriding getRoutingFunction(ErrorAttributes errorAttributes) to handle exception for our functional endpoint. Here we have defined the RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse); so this method will take care of all API if exception occurred in any API it will handle.
If we want to define for any specific API then we need to define API path in getRoutingFunction(ErrorAttributes errorAttributes) like this : return RouterFunctions.route().GET(“/get/students”, this::renderErrorResponse).build(); Now it will handle exception for only specific API “/get/students”.

Watch Video Here :