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 Task Scheduler Example using @Scheduled Annotation
- Spring Boot + Angular 8 CRUD Example
- Difference between @PreAuthorize and @PostAuthorize Annotations in Spring Security
- Spring Boot RESTful Web Service Example
- How to iterate list on JSP in Spring MVC
- Failed to start bean ‘documentationPluginsBootstrapper’; nested exception is java.lang.NullPointerException
- Secondary type Dependency Injection in Spring
- JSP page/file is not rendering in Spring Boot application
- Spring Boot application.properties vs. application.yml
- @ControllerAdvice vs. @RestControllerAdvice in Spring