Start United States USA — software Error Handling in Spring Webflux

Error Handling in Spring Webflux

423
0
TEILEN

Look at error handling in Spring Webflux.
Let’s be friends:
Comment (0)
Join the DZone community and get the full member experience.
The topic of error handling in web applications is very important. From a client perspective it is essential to know on how was the request proceeded and in case of any error is crucial to provide to the client a valid reason, especially if the error was due to the client’s actions. There are different situations, when notifying callers about concrete reasons is important – think about server-side validations, business logic errors that come due to bad requests or simple not found situations.
The mechanism of error handling in Webflux is different, from what we know from Spring MVC. Core building blocks of reactive apps – Mono and Flux brings a special way to deal with error situations, and while old exception-based error handling still may work for some cases, it violates Spring Webflux nature. In this post I will do an overview of how to process errors in Webflux when it comes to business errors and absent data. I will not cover technical errors in this article, as they are handled by Spring framework.
Before we will move to the subject of error handling, let define what we want to achieve. Assume, that we build application using a conventional architecture with a vertical separation by layers and a horizontal separation by domains. That means, that our app consists of three main layers: repositories (one that handle data access), services (one that do custom business logic) and handlers (to work with HTTP requests/responses; understand them as controllers in Spring MVC). Take a look on the graph below and you can note that potentially errors may occur on any layer:
Although, I need to clarify here, that from a technical perspective errors are not same. On the repository level (and let abstract here also clients, that deal with external APIs and all data-access components) usually occur what is called technical errors. For instance, something can be wrong with a database, so the repository component will throw an error. This error is a subclass of RuntimeException and if we use Spring is handled by framework, so we don’t need to do something here. It will result to 500 error code.
An another case is what we called business errors. This is a violation of custom business rules of your app. While it may be considered as not as a good idea to have such errors, they are unavoidable, because, as it was mentioned before, we have to provide a meaningful response to clients in case of such violations. If you will return to the graph, you will note, that such errors usually occur on the service level, therefore we have to deal with them.

Continue reading...