Finally, I am writing another short article that might help a lot of developers.
I would like to talk a little bit about how we can handle errors (Exceptions) and turn them to unified JSON response in Spring Webflux which is reactive.
If you do not want to go to details and like to see the whole code, check this out.
OK, let’s dive into the code:
As you can see, we defined a bean of ErrorWebExceptionHandler and made it first as highest bean order to assure Spring first call this, also we implemented ServerAccessDeniedHandler interface to prevent any libraries handles ServerAccessDenied exception individually. Responsibility of caught function is to iterate on all existing exception handlers (Injected by Spring which provides a list ProblemExceptionHandler implementations) to find out the one that can support/handle the occurred exception and convert it to ProblemVM for HTTP response. Here is the ProblemVM
Next step is to implement the handlers and add it to Spring DI with @Component annotation. We need to have an interface which has two methods, generateProblemVM and supports. As you might guess from their names, the first method is to generate ProblemVM class from the exception message or its stack trace and the second method (supports) returns True or False whether it can handle the given exception.
Here is the interface called ProblemExceptionHandler
Below is only one implementation (HttpStatusCodeException) of the interface. To see more handlers you can check here
Note: Handlers need to be annotated by @Component to tell Spring framework to add it to List<ProblemExceptionHandler<*>> which is injected by ExceptionHandler
Yohooo!, now we are able to handle any type of exception in our reactive server provided by Spring Webflux.
Please feel free to put comments if you think it can be better or you have any suggestions