Suppose I have a Mono<MyObject>
which would be populated by retrieving something from the database or another API. If I got no results from the database or the API returned with an empty body or 404 then I want to execute some logic.
Would I just create a Mono.error()
and handle it like this
Mono<MyObject> myObjectMono = Mono.error(new NotFoundException("Error"));
myObject.doOnError(e -> {
if (e instanceof NotFoundException) {
//my logic for responses when database returns 0 rows or api response is empty/404
}
else {
//other logic here for actual errors
}
}).subscribe(myObject -> {
//my logic when there's a value
});
Or do I use Mono.empty()
? how do I handle empty though? I know there's switchIfEmpty()
but I don't really have anything to return and don't want the subscribe logic to execute.
Mono<MyObject> myObjectMono = Mono.empty();
myObject.subscribe(myObject -> {
//my logic when there's a value
});
Note that the starting point of this is not Http request so there's no client that I will return the Mono to, for simplicity let's just say it's a scheduled job.
Both approaches are technically correct. The direction to take depends on the conventions established in your project. I'd suggest avoiding exceptions if possible because creating exceptions is a heavy operation because of its stack trace.
If you want to go with Mono.empty
you can do it like this:
Mono.<String>empty()
.switchIfEmpty(Mono.fromCallable(() -> {
System.out.println("no response");
return null;
}))
.subscribe(response -> {
System.out.println("response = " + response);
});
If you want to go with exceptions, you can do it like this:
Mono.<String>error(new RuntimeException(""))
.subscribe(
response -> {
System.out.println("response = " + response);
},
error -> {
System.out.println("error = " + error);
}
);
or
Mono.<String>error(new RuntimeException(""))
.doOnError(NotFoundException.class, e -> {
System.out.println("not found exception: " + e);
})
.doOnError(e -> {
System.out.println("another exception: " + e);
})
.subscribe(response -> {
System.out.println("response = " + response);
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments