Skip to content

Instantly share code, notes, and snippets.

@abhi2495
Last active November 5, 2024 23:16
Show Gist options
  • Save abhi2495/4607f2c827b2130ab6e08320f4ca5079 to your computer and use it in GitHub Desktop.
Save abhi2495/4607f2c827b2130ab6e08320f4ca5079 to your computer and use it in GitHub Desktop.
/*
##################################################################################
##################################################################################
######### IF YOU FOUND THIS GIST USEFUL, PLEASE LEAVE A STAR. THANKS. ############
##################################################################################
##################################################################################
*/
@ExceptionHandler(WebClientResponseException.class)
public ResponseEntity handleWebClientException(WebClientResponseException ex){
/*
Here we can write complex conditional logic based on the response status,
by using methods like getStatusCode(), getRawStatusCode(), getStatusText(), getHeaders()
and getResponseBodyAsString().
Also we can get reference of the request that was sent using the method getRequest.
*/
return ResponseEntity.badRequest().body(ex.getResponseBodyAsString());
}
@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();
}

Two approaches to handle error responses from Spring WebClient calls globally:

  • Exceptions with webclients are all wrapped in WebClientResponseException class. So we can handle that using Spring's ExceptionHandler annotation.

  • Using ExchangeFilterFunction while constructing the webclient bean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment