我撰寫了使用 webclient 呼叫另一個端點并希望添加反應式錯誤處理的代碼。但是,似乎我對 doOnError 或 one rrorResume 的理解可能不正確:
webClient
.get()
.uri(someUri)
.retrieve()
.bodyToFlux(Some.class)
.onErrorResume(throwable -> {
log.error("Error occurred when calling other service: {}", throwable.getMessage());
return Flux.error(new RunTimeException("Exception type: " throwable.getClass() " Exception message: " throwable.getMessage()));
});
然后意圖是這個呼叫實際上是呼叫它的更大反應鏈的一部分,如果在運行 api 呼叫(.get().retrieve())時拋出例外,onErrorResume應該拋出例外并將例外傳遞給更高級別的反應鏈呼叫者。
我試圖通過以下方式對它的有效性進行單元測驗:
Mockito.when(webClient.get().uri(URI.create(uri)).retrieve()).thenThrow(new RuntimeException("Hello world exception thrown"));
但注意到例外只是被拋出,并且代碼在反應鏈的 .retrieve 步驟終止,而不是繼續執行該onErrorResume步驟。
uj5u.com熱心網友回復:
這是因為您的測驗在構建 Mono 時會引發錯誤retrieve,而不是回傳一個在訂閱時立即發出錯誤的功能 Mono。因此,出錯的不是您的資料流,而是處理資料流本身的管道。
您可以通過回傳一個來解決這個問題Mono.error:
Mockito.when(webClient.get().uri(URI.create(uri)).retrieve())
.thenReturn(Mono.error(new RuntimeException("Hello world exception thrown")));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/527380.html
標籤:春天模仿者spring-webflux项目反应堆反应堆
上一篇:郵件地址檢查
