I need to know how to throw an exception explicitly while executing the Mono. I'm not able to subscribe, block Mono because it has end (down-stream) subscriber. Just need to validate the data and throw exception explicitly to perform retry.
public Mono<Response> handleResponse() {
return userService.getUser()
.doOnNext(response -> validate(response.getData()))
.onErrorResume(ex -> {
// not working
throw Exceptions.propagete(ex);
});
}
private void validate() {
.....
throw new RuntimeException();
}
@Retyable(value = {RuntimeException.class})
If no exception, it will return Mono to next level. I can use Mono retry itself but need to know is there any way to solve this.
To produce an error you can use Mono.error(throwable)
.
But the another problem in your code that you do the validation in doOnNext
, which is not supposed to change the flow. Better to use flatMap
.
You can do something like:
userService.getUser()
.flatMap(response -> {
try {
validate(response.getData());
return Mono.just(response);
} catch (Throwable t) {
return Mono.error(t);
}
})
The simplest way would be the following:
getUser()
.map(response -> {
validate(response);
return response;
})
If it's possible for you to make changes to the validate
method, I would suggest doing it in the following manner:
getUser()
.handle((response, sink) -> {
if (isValid(response)) {
sink.next(response);
} else {
sink.error(new RuntimeException("..."));
}
})
// where
public boolean isValid(User user) {
//...
}
What if you try something like this:
public Mono<Response> handleResponse() {
return Mono.fromFuture(userService.getUser()
.doOnNext(response -> validate(response.getData()))
.handle((response, throwable) -> {
if (throwable == null) {
return response;
} else {
throw new RuntimeException();
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.