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
- Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping Annotation Example
- Spring Security JDBC authentication with Spring Boot
- Spring Web MVC (Model View Controller) Introduction and Features
- How to load multiple bean configuration files in Spring
- Spring Autowiring Example using XML