如何在WebClient检索中处理404 [英] How to handle 404 in webclient retrive
本文介绍了如何在WebClient检索中处理404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Spring WebClient的新手,我已经编写了一个泛型方法,可用于在我的应用程序中使用REST API:
public <T> List<T> get(URI url, Class<T> responseType) {
return WebClient.builder().build().get().uri(url)
.header("Authorization", "Basic " + principal)
.retrieve().bodyToFlux(responseType).collectList().block();
}
如果使用REST-API返回404,我想返回并清空列表。
有人能建议如何做到这一点吗?
推荐答案
默认情况下,retrieve方法对任何4xx&;5xx错误抛出WebClientResponseException异常
默认情况下,4xx和5xx响应会导致WebClientResponseException。
您可以使用onErrorResume
webClient.get()
.uri(url)
.retrieve()
.header("Authorization", "Basic " + principal)
.bodyToFlux(Account.class)
.onErrorResume(WebClientResponseException.class,
ex -> ex.getRawStatusCode() == 404 ? Flux.empty() : Mono.error(ex))
.collectList().block();
这篇关于如何在WebClient检索中处理404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文