title: How can I safely throw exceptions from within a DelegatingHandler
body: <p>I have a delegating handler that throws specific exceptions based on fault messages received from the server.
  This allows the client to retry (using polly, but as you'll see the mechanism doesn't matter)
  After two failed attempts the third attempt simply hangs. No data hits the server, and nothing further happens. This seems to be because the HttpClient has a max of two connections, which suggests these connections are not being closed properly.
  Is there something I can do to close the connection or should I change the design so that the delegating handlers do not throw exceptions?</p>
  
  <p>See simple example below to reproduce</p>
  
  <pre><code>private class Test : DelegatingHandler
  {
      protected override async Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
      {
          var response = await base.SendAsync(request, cancellationToken);
  
          throw new Exception("afesaf");
      }
  }
  
  [HttpGet]
  [Route("B")]
  public async Task B()
  {
      var handler = new HttpClientHandler();
      var pipeline = HttpClientFactory.CreatePipeline(handler, new[] { new Test() });
  
      var http = new HttpClient(pipeline);
  
      http.BaseAddress = new Uri("http://google.com");
  
      var count = 0;
      while (count++ &lt; 5)
      try
      {
          Log.Info("A");
          var request = new HttpRequestMessage(HttpMethod.Get, "");
          await http.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None).ConfigureAwait(false);
      }
      catch
      {
  
      }
  }
  </code></pre>