I want to make exception handler for my WebClient, which calls external API. I don't want to use onStatus() method, due to I have abstract web client with different methods where I have to process exceptions, so I have to copy paste each onStatus() in my every abstract method. I want to make something similar to the rest template approach: we can implement ResponseErrorHandler and add our implementation into resttemplate e.g. setExceptionHandler(ourImplementation). I want the one class to handle all the exceptions. Thanks for your advice in advance!
@Bean
public WebClient buildWebClient() {
Function<ClientResponse, Mono<ClientResponse>> webclientResponseProcessor =
clientResponse -> {
HttpStatus responseStatus = clientResponse.statusCode();
if (responseStatus.is4xxClientError()) {
System.out.println("4xx error");
return Mono.error(new MyCustomClientException());
} else if (responseStatus.is5xxServerError()) {
System.out.println("5xx error");
return Mono.error(new MyCustomClientException());
}
return Mono.just(clientResponse);
};
return WebClient.builder()
.filter(ExchangeFilterFunction.ofResponseProcessor(webclientResponseProcessor)).build();
}
We can use ResponseProcessor to write logic and handle different http statuses. This solution was tested and it works.