Error Handling with WebClient in Spring Boot

When developing reactive applications with Spring Boot and using the WebClient to make web requests, custom error handling is an essential aspect of ensuring robust and user-friendly applications. In this article, we’ll explore how to use the onErrorMap method with the WebClient to handle and customize error responses.
Error Handling with onErrorMap
The onErrorMap method is a powerful tool for mapping and transforming error signals into other error signals or exceptions. It provides fine-grained control over how errors are handled in your application. Let’s dive into some practical examples to illustrate its usage.
Example 1: Mapping a Specific Exception to Another Exception
Suppose you’re interacting with an API, and you want to catch a specific exception, such as ResourceNotFound, and transform it into a custom exception with a more user-friendly error message. Here’s how you can do it:
webClient.get()
.uri("URL")
.retrieve()
.bodyToMono(MyResponse.class)
.onErrorMap(ResourceNotFound.class, ex -> new AnotherException("Another Exception", ex))
Example 2: Mapping Any Exception to a Generic Error Exception
In some cases, you may want to catch any exception and map it to a generic error exception with a standard error message. Here’s how you can achieve that:
webClient.get()
.uri("URL")
.retrieve()
.bodyToMono(MyResponse.class)
.onErrorMap(AnyException.class, ex -> new Exception("Generic exception", ex));
Example 3: Mapping Status Code-Based Errors
Sometimes, you need to handle errors based on HTTP status codes, such as 4xx client errors or 5xx server errors. You can use `onStatus` to achieve this:
public Mono<ReturnedItem> nonStatusError(String host, int port, String path){
return webClient.get().uri(uriBuilder -> uriBuilder.host(host).port(port).path(path).build()).retrieve()
.onStatus(HttpStatus::isError,
response -> switch (response.rawStatusCode()){
case 400 -> Mono.error(new BadRequestException("bad request made"));
case 401, 403 -> Mono.error(new Exception("auth error"));
case 404 -> Mono.error(new Exception("Maybe not an error?"));
case 500 -> Mono.error(new Exception("server error"));
default -> Mono.error(new Exception("something went wrong"));
})
.bodyToMono(ReturnedItem.class)
.onErrorMap(Throwable.class, throwable -> new Exception("plain exception"));
}
webClient.get()
.uri("URL")
.retrieve()
.onStatus(HttpStatus::is4xxClientError, clientResponse -> Mono.error(new ClientErrorException("Client error")))
.onStatus(HttpStatus::is5xxServerError, clientResponse -> Mono.error(new ServerErrorException("Server error")))
.bodyToMono(MyResponse.class);
Using Spring Boot’s WebClient and onErrorMap, developers can improve application reliability and user-friendliness by customizing error handling, including dealing with specific problems and HTTP status code errors.