Spring Boot – Handling Errors in WebClient


In this guide, we’ll learn how to handle WebClient errors. The retrieve() method in WebClient throws a WebClientResponseException whenever the API response with status code 4xx or 5xx is received.

We can use onStatus(Predicate<HttpStatus> statusPredicate, Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) method to handle or customize the exception. We recommend, go through the Spring Boot– Consuming a REST Services with WebClient article before proceeding.

1. Handling 4xx Errors

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. Handling 5xx Errors

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. Handling 4xx & 5xx together

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

References

  1. Spring Boot– Consuming a REST Services with WebClient
  2. Spring WebFlux

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.