kotlinx-coroutines-reactive
makes org.reactivestreams.Publisher
to have awaitXXX
methods:
val person = peopleReactiveRepository.findById(personId).awaitSingle()
If there is no person can be found by a person ID, this invocation will throw NoSuchElementException and this exception cannot be handled in the user code directly. And Spring MVC ExceptionHandler
can not translate this exception into a user-friendly response.
java.util.NoSuchElementException: No value received via onNext for awaitSingle
at kotlinx.coroutines.experimental.reactive.AwaitKt$awaitOne$$inlined$suspendCancellableCoroutine$lambda$1.onComplete(Await.kt:131) ~[kotlinx-coroutines-reactive-0.22.1.jar:na]
at reactor.core.publisher.StrictSubscriber.onComplete(StrictSubscriber.java:123) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:1327) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.FluxHide$SuppressFuseableSubscriber.onComplete(FluxHide.java:137) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.FluxMap$MapSubscriber.onComplete(FluxMap.java:130) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:96) ~[reactor-core-3.1.2.RELEASE.jar:3.1.2.RELEASE]
at com.mongodb.reactivestreams.client.internal.ObservableToPublisher$1.onComplete(ObservableToPublisher.java:78) ~[mongodb-driver-reactivestreams-1.6.0.jar:na]
One of approaches I can figure out is in the following:
val person = peopleRepository.findById(personId).awaitFirstOrDefault(null)
if (person == null) {
// do something
}
But I do not think it is an elegant way. For example, can provide a method named awaitSingleOptional
.
Is there any better Kotlin way to handle this scenario?