Spring Boot – 处理 WebClient 中的错误

x33g5p2x  于2021-10-16 转载在 Spring  
字(1.1k)|赞(0)|评价(0)|浏览(965)

在本指南中,我们将学习如何处理 WebClient 错误。 每当收到状态代码为 4xx5xx 的 API 响应时,WebClient 中的 retrieve() 方法就会抛出一个 WebClientResponseException

我们可以使用 onStatus(Predicate<HttpStatus> *statusPredicate*, Function<ClientResponse, Mono<? *extends* Throwable>> *exceptionFunction*) 方法来处理或自定义异常。 我们建议在继续之前阅读 Spring Boot – 使用 WebClient 使用 REST 服务一文。

1. 处理 4xx 错误

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();	 
}

2. 处理 5xx 错误

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();	 
}

3. 一起处理 4xx 和 5xx

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();	 
}

相关文章

微信公众号

最新文章

更多