在本指南中,我们将学习如何处理 WebClient 错误。 每当收到状态代码为 4xx 或 5xx 的 API 响应时,WebClient
中的 retrieve()
方法就会抛出一个 WebClientResponseException
。
我们可以使用 onStatus(Predicate<HttpStatus> *statusPredicate*, Function<ClientResponse, Mono<? *extends* Throwable>> *exceptionFunction*)
方法来处理或自定义异常。 我们建议在继续之前阅读 Spring Boot – 使用 WebClient 使用 REST 服务一文。
public Post getPost() {
return webClientBuilder.build()
.get()
.uri(POST_OF_API)
.retrieve()
.onStatus(HttpStatus::is4xxClientError,
error -> Mono.error(new RuntimeException("API not found")))
.bodyToMono(Post.class)
.block();
}
public Post getPost() {
return webClientBuilder.build()
.get()
.uri(POST_OF_API)
.retrieve()
.onStatus(HttpStatus::is5xxServerError,
error -> Mono.error(new RuntimeException("Server is not responding")))
.bodyToMono(Post.class)
.block();
}
public Post getPost() {
return webClientBuilder.build()
.get()
.uri(POST_OF_API)
.retrieve()
.onStatus(HttpStatus::is4xxClientError,
error -> Mono.error(new RuntimeException("API not found")))
.onStatus(HttpStatus::is5xxServerError,
error -> Mono.error(new RuntimeException("Server is not responding")))
.bodyToMono(Post.class)
.block();
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/spring/spring-boot-handling-errors-in-webclient
内容来源于网络,如有侵权,请联系作者删除!