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 Constructor-based Dependency Injection Example
- Spring Boot- Pagination and Sorting using Spring Data JPA
- Spring MVC @Controller, @RequestMapping, @RequestParam, and @PathVariable Annotation Example
- @ConfigurationProperties Annotation in Spring Boot
- Spring AOP Before Advice example using XML configuration
- Secondary type Dependency Injection in Spring
- Spring @RestController, @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping Annotation Example
- Simplify Data Access with Spring’s @Repository Annotation
- Difference Between @Component and @ComponentScan Annotations in Spring Boot
- Difference between @PreAuthorize and @PostAuthorize Annotations in Spring Security