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
Similar Posts
- How to read properties file in Spring
- @ControllerAdvice vs. @RestControllerAdvice in Spring
- Spring Boot Security- Remember Me Example
- Spring Boot + Activiti Service Task Example
- @ConfigurationProperties Annotation in Spring Boot
- How to insert image in database using Spring MVC
- Getting Started with Spring Boot and MongoDB
- Securing Passwords with Spring Security Password Encoder
- Spring Boot- The Tomcat connector configured to listen on port 8080 failed to start
- Spring MVC Database Connectivity Example using Annotation and Java Based Configuration