Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wubin1989/029abf39e787dc05beda0460129c8876 to your computer and use it in GitHub Desktop.
Save wubin1989/029abf39e787dc05beda0460129c8876 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