title: Java Spring Boot framework - WebClient logging 4xx/5xx body response
body: <p>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 <code>clientResponse</code> as a <code>String</code>, and we can later using <code>gson</code> to serialize it?</p>
  <pre class="lang-java prettyprint-override"><code>
  String postResponse =
          post(
              ENDPOINT,
              token,
              request,
              Request.class);
  
  Response response = gson.fromJson(postResponse, Response.class);
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>
      private String post(String endpoint, String token, Mono&lt;?&gt; requestBody, Class&lt;?&gt; requestBodyClass) {
  
        WebClient.Builder webClientBuilder = WebClient.builder();
  
        WebClient.RequestBodySpec requestBodySpec = webClientBuilder.build().post().uri(uri);
        requestBodySpec.header(
            &quot;Authorization&quot;, BEARER_TOKEN_PREFIX + this.accessTokens.get(token));
  
        return requestBodySpec
          .header(&quot;Content-Type&quot;, HEADER_VALUE_CONTENT_TYPE)
          .body(Mono.just(requestBody), requestBodyClass)
          .retrieve()
          .bodyToMono(String.class)
          .block();
      }
  </code></pre>