title: How to modify the response body in Spring Cloud Gateway just before the commit
body: <p>I'm using Spring Cloud Gateway with Spring 5, Spring Reactor and Netty for a project. For every request send to the gateway I want to do something just before the response is sent to the client. The best way I have found to do it is to add an action to the response with the beforeCommit method.</p>
  
  <p>I first tried this approach :</p>
  
  <pre><code>        exchange.getResponse().beforeCommit(() -&gt; {
              ServerHttpResponse response = exchange.getResponse();
              try {
                  myActionDoneHere();
                  response.setStatusCode(OK);
                  return Mono.empty();
              } catch (Exception ex) {
                  return Mono.error(new MyException(ex));
              }
          });
  </code></pre>
  
  <p>And tried to handle the exception in an exception handler :</p>
  
  <pre><code>public Mono&lt;Void&gt; handle(ServerWebExchange exchange, Throwable ex) {
      if (isMyException(ex)) {
       exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
          exchange.getResponse().getHeaders().setContentLength(MSG.length());
          exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
          return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(MSG.getBytes())));
      }
  
      return Mono.error(ex);
  }
  </code></pre>
  
  <p>When I do that I have an exception when I try to modify the content length. If I understand well the situation. I can't modify the response anymore in my handler because the it as been already committed. So I tried an other solution and tried to modify the response in my action executed just before the commit :</p>
  
  <pre><code>exchange.getResponse().beforeCommit(() -&gt; {
      ServerHttpResponse response = exchange.getResponse();
      try {
          myActionDoneHere();
          response.setStatusCode(OK);
          return Mono.empty();
      } catch (Exception ex) {
          response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
          response.getHeaders().setContentLength(MSG.length());
          response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
          return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(MSG.getBytes())));
      }
  });
  </code></pre>
  
  <p>This time I don't have any exception, I can modify the content length but I can't modify the body of the response.</p>
  
  <p>So does someone know if it's possible to do so and How ?</p>