简体   繁体   中英

Java Spring Boot framework - WebClient logging 4xx/5xx body response

I am new to Spring Boot framework's WebClient. How do I only log the 4xx/5xx with its error body only on error, but when success, return back the clientResponse as a String , and we can later using gson to serialize it?


String postResponse =
        post(
            ENDPOINT,
            token,
            request,
            Request.class);

Response response = gson.fromJson(postResponse, Response.class);

    private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {

      WebClient.Builder webClientBuilder = WebClient.builder();

      WebClient.RequestBodySpec requestBodySpec = webClientBuilder.build().post().uri(uri);
      requestBodySpec.header(
          "Authorization", BEARER_TOKEN_PREFIX + this.accessTokens.get(token));

      return requestBodySpec
        .header("Content-Type", HEADER_VALUE_CONTENT_TYPE)
        .body(Mono.just(requestBody), requestBodyClass)
        .retrieve()
        .bodyToMono(String.class)
        .block();
    }

May I suggest something like:

    private String post(String endpoint, String token, Mono<?> requestBody, Class<?> requestBodyClass) {
        Mono<String> stringMono = WebClient.builder().build()
                .post()
                .uri(endpoint)
                .body(BodyInserters.fromValue(requestBodyClass))
                .exchange()
                .flatMap(SomeServiceImpl::getResultAsStringOrLog4xx5xx);
        
        //get the JSON from the Mono, but you might not want to block
    }

(I omitted the headers)

And the actual answer to the question, do perform the logging with something similar:

private static Mono<String> getResultAsStringOrLog4xx5xx(ClientResponse response) {
        if (response.statusCode().is2xxSuccessful()) {
            return response.bodyToMono(String.class);
        } else if (response.statusCode().is5xxServerError()) {
            Logger.error(); //up to you
        } else {
//at this point, you can have your logic on error code
        }
        return
    }

There are other ways of doing this, hope this can get you started.

Also, try not to block() in your application.

Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM