-
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.
Last active
November 5, 2024 23:16
-
-
Save abhi2495/4607f2c827b2130ab6e08320f4ca5079 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
################################################################################## | |
################################################################################## | |
######### 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()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment