title: How do I ensure DelegatingHandlers throw exceptions on timeouts?
body: <p>I'm using <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.postasync(v=vs.118).aspx" rel="nofollow">HttpClient's PostAnsyc</a> method to synchronously call a REST API from service code invoked by my MVC application, but I'm losing exceptions in a DelegatingHandler.</p>
  
  <p>The usage is synchronous. I am aware of the async path and it does not fit my use case.</p>
  
  <p>Here are some variant's I've tried that didn't throw exceptions on timeout:</p>
  
  <pre><code>//controller action
  [HttpPost]
  public JsonResult Foo(int id)
  {
      try
      {
          var result = _businessService.Foo(id);
          return Json(result, JsonRequestBehavior.DenyGet);
      }
      catch(Exception exception)
      {
          return Json(exception, JsonRequestBehavior.DenyGet);
      }
  }
  
  //infrastructure code deep in my application
  public HttpResponseMessage Post(Uri uri, StringContent content)
  {
      return _httpClient.PostAsync(uri, content).Result;
  }
  
  //DelegatingHandler code
  protected override Task&lt;HttpResponseMessage&gt; SendAsync(
      HttpRequestMessage request,
      CancellationToken cancellationToken)
  {
      var taskCompletionSource = new TaskCompletionSource&lt;HttpResponseMessage&gt;();
      base.SendAsync(request, cancellationToken)
          .ContinueWith( t =&gt;
          {
              if (t.IsFaulted)
              {
                  if(t.Exception != null)
                  {
                      taskCompletionSource.TrySetException(t.Exception);
                  }
              }
              else if (t.IsCanceled)
              {
                  taskCompletionSource.TrySetCanceled();
              }
              else
              {
                  try
                  {
                      LogResponse(t.Result);
                      taskCompletionSource.SetResult(t.Result);
                  }
                  catch (Exception ex)
                  {
                      taskCompletionSource.TrySetException(ex);
                  }
              }
          }, cancellationToken);
      return taskCompletionSource.Task;
  }
  </code></pre>
  
  <p>How do I ensure that my DelegatingHandlers do not swallow exceptions during a timeout?</p>