![](/img/trans.png)
[英]How to perform an action only if the Mono is empty and throw an error if not empty
[英]How to throw an Error explicitly while processing Mono
我需要知道如何在執行 Mono 時顯式拋出異常。我無法訂閱,阻止 Mono,因為它有結束(下游)訂閱者。 只需要驗證數據並顯式拋出異常來執行重試。
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})
如果沒有異常,它將返回 Mono 到下一級。 我可以使用 Mono 重試,但需要知道有什么辦法可以解決這個問題。
要產生錯誤,您可以使用Mono.error(throwable)
。
但是代碼中的另一個問題是您在doOnNext
中進行驗證,這不應該改變流程。 最好使用flatMap
。
你可以這樣做:
userService.getUser()
.flatMap(response -> {
try {
validate(response.getData());
return Mono.just(response);
} catch (Throwable t) {
return Mono.error(t);
}
})
最簡單的方法如下:
getUser()
.map(response -> {
validate(response);
return response;
})
如果您可以更改validate
方法,我建議您按以下方式進行:
getUser()
.handle((response, sink) -> {
if (isValid(response)) {
sink.next(response);
} else {
sink.error(new RuntimeException("..."));
}
})
// where
public boolean isValid(User user) {
//...
}
如果你嘗試這樣的事情怎么辦:
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();
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.