web.reactive.function.server.ServerRequest.awaitBody() exception handling #30926
Labels
in: web
Issues in web modules (web, webmvc, webflux, websocket)
status: declined
A suggestion or change that we don't feel we should currently apply
theme: kotlin
An issue related to Kotlin support
Affects: Spring v6.0.6
What is the recommended approach on handling ServerRequest.awaitBody()
Right now, the API is using under the hood
awaitSingle()
fromkotlinx.coroutines.reactive
, which is intentional fromthe spring team. Now, the API is throwing either
NoSuchElementException
orIllegalArgmuentException
depending on ifthe publisher emits zero or more than one values.
Question: In general code, are we expected to catch them both? Although, the operator is being used on a
Mono
,which technically can never throw
IllegalArgmuentException
?On the other hand, since we always extract the body (thus we are not directly affected by how a client writes in body)
in either a
Flux
orMono
if the client emits more than one values, but we useServerRequest.awaitBody()
the bodyis converted properly, and we are retrieving a collection. Though, this process breaks in serialization
(as expected).
Usage in general code
The most "blur" part is about throwing
IllegalArgmuentException
. That is because, when usingkotlinx.serialization
for general "catch-all" around deserialization it is recommended to catch
IllegalArgmuentException
. In that case, wehave to know beforehand if we need to also check if
IllegalArgmuentException
is type ofSerializationException
(so we can distinguish between them).
When I am writing code to handle
ServerRequest.awaitBody()
, I find it a one-way path to useServerRequest.awaitBodyOrNull()
API to avoid all the above points.My exception handling looks like this:
Which makes
ServerRequest.awaitBody()
kind of "obsolete" API (at least imho).Proposal
I recommend to at least document about the fact that
ServerRequest.awaitBody()
throws exceptions which are expected to be caught from the user.Also, happy to provide a pr with the changes.
The text was updated successfully, but these errors were encountered: