title: CompletableFuture compose for exceptions
body: <p>The <code>CompletableFuture</code> API allows us to use <code>thenCompose</code> to chain another future:</p>
  
  <pre class="lang-java prettyprint-override"><code>CompletableFuture&lt;String&gt; future1 = submit("foo");
  CompletableFuture&lt;String&gt; future2 = future.thenCompose((result) -&gt; submit(result));
  </code></pre>
  
  <p>This only works for successful responses though. Is there a way to do the same but also including exception handling?</p>
  
  <p>For example:</p>
  
  <pre class="lang-java prettyprint-override"><code>CompletableFuture&lt;String&gt; future1 = submit("foo");
  CompletableFuture&lt;String&gt; future2 = future.handleCompose((result, error) -&gt; {
    if (error != null)
      return submit("failure"); // Handle error by doing a different action with the same result (like a fallback)
    else
      return submit(result);
  });
  </code></pre>
  
  <p>I know you can do something like <code>whenComplete</code>:</p>
  
  <pre class="lang-java prettyprint-override"><code>CompletableFuture&lt;String&gt; future2 = new CompletableFuture&lt;&gt;();
  CompletableFuture&lt;String&gt; future1 = submit("foo");
  future.whenComplete((result, error) -&gt; {
    CompletableFuture&lt;String&gt; tmp;
    if (error != null)
      tmp = submit("failure");
    else
      tmp = submit(result);
    tmp.whenComplete((result2, error2) -&gt; {
      if (error2 != null) future2.completeExceptionally(error2);
      else future2.complete(result2);
    });
  });
  </code></pre>
  
  <p>This however loses the ability to cancel properly and seems like a very "hacky" solution compared to the success composition handling. Is there a good way that does not require making my own extension of the CompletableFuture class?</p>
  
  <p>The problem is that I need to return a single future from my method and it should be capable to cancel the entire process at any point in time.</p>