title: Catch exception in async Task
body: <p>I'm working in C# (console application).</p>
  
  <p>In my program, I have to contact a httpClient. First I check if the client is responding using <code>GetAsync</code>. So my request method is async, making my Task async.</p>
  
  <p>When client doesn't respond (or something else) it throw an exception but i'm unable to catch it.</p>
  
  <p>I added a <code>ContinueWith</code> but it doesn't work. With a breackpoint I saw that the piece of code is reached at the start of my Task so the exception is always null.</p>
  
  <p>How can I solve this problem ?</p>
  
  <p>There is my code :</p>
  
  <pre><code>static void Run()
  {
      String urlRequest = "";
      CancellationTokenSource cts = new CancellationTokenSource();
      CancellationToken ct = cts.Token;
  
      Console.WriteLine($"Program running, press a key to stop");
      try
      {
          Task task = Task.Factory.StartNew(async () =&gt;
          {
              using (HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential("user", "pass") })
              {
                  HttpClient client = new HttpClient(handler);
                  client.BaseAddress = new Uri(urlRequest);
                  client.DefaultRequestHeaders.Accept.Clear();
                  bool serviceAvailable = await CheckService(client);
                  if (serviceAvailable)
                  {
                      bool doLoop = true;
                      while (doLoop)
                      {
                          // Do something
  
                          Thread.Sleep(100);
                          if (ct.IsCancellationRequested)
                          {
                              Console.WriteLine("\r\ntask cancelled");
                              break;
                          }
                      }
                  }
                  else
                  {
                      throw new HttpRequestException($"Unable to contact service at {urlRequest}");
                  }
              }
  
          }, ct).ContinueWith(tsk =&gt;
          {
              if (tsk.Exception != null)
                  throw tsk.Exception;
          });
  
          Console.ReadKey();
          cts.Cancel();
          Thread.Sleep(1000);
      }
      catch (Exception e)
      {
          Log(e);
      }
  }
  
  static async Task&lt;bool&gt; CheckClient(HttpClient client)
  {
      Console.WriteLine("Check service Call ...");
      HttpResponseMessage response = await client.GetAsync("CheckService");
      if (response.IsSuccessStatusCode)
      {
          return true;
      }
  
      return false;
  }
  </code></pre>