[英]HTTP Response Exception Handling in Spring 5 Reactive
我正在使用Spring Boot 2和Spring 5開發一些帶有WebFlux反應啟動器的反應式微服務。
我遇到了以下問題:我想處理從調用另一個REST服務收到的所有HTTP狀態,並在收到一些錯誤的HTTP狀態時拋出異常。 例如,當我調用端點並收到404 HTTP狀態時,我想拋出一個異常,並在一些ExceptionHandler類中處理該異常,就像在Spring 4中使用@ControllerAdvice
。
這樣做的正確方法是什么? 希望收到一些好的建議。
這可以通過兩個獨立的部分來解決。
使用WebClient
,您可以從遠程服務接收HTTP 404響應。 默認情況下,所有4xx
和5xx
客戶端響應都將變為WebClientResponseException
。 因此,您可以直接在WebFlux應用程序中處理這些異常。
如果您只想將404響應轉換為自定義例外,則可以執行以下操作:
WebClient webClient = //...
webClient.get().uri("/persons/1")
.retrieve()
.onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),
clientResponse -> Mono.error(new MyCustomException()))
.bodyToMono(...);
這顯然是基於每個客戶呼叫完成的。
您可以使用ExchangeFilterFunction
以更可重用的方式實現相同的功能,您可以在WebClient
實例上一勞永逸地設置,如下所示:
WebClient.builder().filter(myExchangeFilterFunction)...
隨着春天WebFlux與注釋,您可以處理與注解的方法例外@ExceptionHandler
(見Spring Framework的參考文檔 )。
注意:使用WebExceptionHandler
是可能的,但它的級別很低,因為你沒有高級支持:你需要手動編寫帶緩沖區的響應,而不需要任何序列化支持。
我認為你要找的是WebFluxResponseStatusExceptionHandler
檢查這個以供參考 。
在WebHandler API中,WebExceptionHandler可用於處理來自WebFilter鏈和目標WebHandler的異常。 使用WebFlux配置時,注冊WebExceptionHandler就像將其聲明為Spring bean一樣簡單,並可選擇通過bean聲明上的@Order或通過實現Ordered來表示優先級。
這個例子可能有所幫助,我自己沒試過。
@Component
@Order(-2)
class RestWebExceptionHandler implements WebExceptionHandler{
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
if (ex instanceof PostNotFoundException) {
exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
// marks the response as complete and forbids writing to it
return exchange.getResponse().setComplete();
}
return Mono.error(ex);
}
}
class PostNotFoundException extends RuntimeException {
PostNotFoundException(String id) {
super("Post:" + id + " is not found.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.