Skip to content

Instantly share code, notes, and snippets.

@Ananto30
Last active January 28, 2020 16:33
Show Gist options
  • Save Ananto30/641fac46a7e359776ebe949aca4da88b to your computer and use it in GitHub Desktop.
Save Ananto30/641fac46a7e359776ebe949aca4da88b to your computer and use it in GitHub Desktop.
public abstract class AbstractWebClient {
private static final String MIME_TYPE = "application/json";
private final WebClient webClient;
public AbstractWebClient(String clientUrl) {
this.webClient = WebClient.builder()
.baseUrl(clientUrl)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MIME_TYPE)
.build();
}
public <T> Mono<T> get(String uri, Class<T> tClass) {
return webClient.get()
.uri(uri)
.header("X-B3-TRACEID", MDC.get("X-B3-TraceId"))
.retrieve()
.onStatus(HttpStatus::is4xxClientError, this::get4xxError)
.onStatus(HttpStatus::is5xxServerError, this::get5xxError)
.bodyToMono(tClass);
}
public <T> Mono<T> post(String uri, Object body, Class<T> tClass) {
return webClient.post()
.uri(uri)
.header("X-B3-TRACEID", MDC.get("X-B3-TraceId"))
.syncBody(body)
.retrieve()
.onStatus(HttpStatus::is4xxClientError, this::get4xxError)
.onStatus(HttpStatus::is5xxServerError, this::get5xxError)
.bodyToMono(tClass);
}
private <T> Mono<T> get4xxError(ClientResponse clientResponse) {
return Mono.error(new Client4xxException("Client Error"));
}
private <T> Mono<T> get5xxError(ClientResponse clientResponse) {
return Mono.error(new Client5xxException("Server Error"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment