title: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification calling Autorest generated code
body: <p>I have a unit test, calling a service that makes use of Autorest generated code to call my Api.</p>
  
  <p>I want my unit test to display the error that my Api is throwing, but there seems to be an error in the service's error handling.</p>
  
  <p>I am using the following command to generate code to consume my api.</p>
  
  <pre><code>autorest --input-file=https://mywebsite.com.au:4433/myapi/api-docs/v1/swagger.json --output-folder=generated --csharp --namespace=MyConnector
  </code></pre>
  
  <p>The generated "client code" contains</p>
  
  <pre><code>    /// &lt;param name='request'&gt;
      /// &lt;/param&gt;
      /// &lt;param name='customHeaders'&gt;
      /// Headers that will be added to request.
      /// &lt;/param&gt;
      /// &lt;param name='cancellationToken'&gt;
      /// The cancellation token.
      /// &lt;/param&gt;
      /// &lt;exception cref="HttpOperationException"&gt;
      /// Thrown when the operation returned an invalid status code
      /// &lt;/exception&gt;
      /// &lt;exception cref="SerializationException"&gt;
      /// Thrown when unable to deserialize the response
      /// &lt;/exception&gt;
      /// &lt;return&gt;
      /// A response object containing the response body and response headers.
      /// &lt;/return&gt;
      public async Task&lt;HttpOperationResponse&lt;GetAvailableCarriersResponse&gt;&gt; GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync(GetAvailableCarriersRequest request = default(GetAvailableCarriersRequest), Dictionary&lt;string, List&lt;string&gt;&gt; customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
      {
          // Tracing
          bool _shouldTrace = ServiceClientTracing.IsEnabled;
          string _invocationId = null;
          if (_shouldTrace)
          {
              _invocationId = ServiceClientTracing.NextInvocationId.ToString();
              Dictionary&lt;string, object&gt; tracingParameters = new Dictionary&lt;string, object&gt;();
              tracingParameters.Add("request", request);
              tracingParameters.Add("cancellationToken", cancellationToken);
              ServiceClientTracing.Enter(_invocationId, this, "GetAvailableCarriersByJobHeaderId", tracingParameters);
          }
          // Construct URL
          var _baseUrl = BaseUri.AbsoluteUri;
          var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/shipping-management/Get-Available-Carriers").ToString();
          // Create HTTP transport objects
          var _httpRequest = new HttpRequestMessage();
          HttpResponseMessage _httpResponse = null;
          _httpRequest.Method = new HttpMethod("POST");
          _httpRequest.RequestUri = new System.Uri(_url);
          // Set Headers
  
  
          if (customHeaders != null)
          {
              foreach(var _header in customHeaders)
              {
                  if (_httpRequest.Headers.Contains(_header.Key))
                  {
                      _httpRequest.Headers.Remove(_header.Key);
                  }
                  _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
              }
          }
  
          // Serialize Request
          string _requestContent = null;
          if(request != null)
          {
              _requestContent = SafeJsonConvert.SerializeObject(request, SerializationSettings);
              _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
              _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8");
          }
          // Send Request
          if (_shouldTrace)
          {
              ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
          }
          cancellationToken.ThrowIfCancellationRequested();
          _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
          if (_shouldTrace)
          {
              ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
          }
          HttpStatusCode _statusCode = _httpResponse.StatusCode;
          cancellationToken.ThrowIfCancellationRequested();
          string _responseContent = null;
          if ((int)_statusCode != 200)
          {
              var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
              if (_httpResponse.Content != null) {
                  _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
              }
              else {
                  _responseContent = string.Empty;
              }
              ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
              ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
              if (_shouldTrace)
              {
                  ServiceClientTracing.Error(_invocationId, ex);
              }
              _httpRequest.Dispose();
              if (_httpResponse != null)
              {
                  _httpResponse.Dispose();
              }
              throw ex;
          }
          // Create Result
          var _result = new HttpOperationResponse&lt;GetAvailableCarriersResponse&gt;();
          _result.Request = _httpRequest;
          _result.Response = _httpResponse;
          // Deserialize Response
          if ((int)_statusCode == 200)
          {
              _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
              try
              {
                  _result.Body = SafeJsonConvert.DeserializeObject&lt;GetAvailableCarriersResponse&gt;(_responseContent, DeserializationSettings);
              }
              catch (JsonException ex)
              {
                  _httpRequest.Dispose();
                  if (_httpResponse != null)
                  {
                      _httpResponse.Dispose();
                  }
                  throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
              }
          }
          if (_shouldTrace)
          {
              ServiceClientTracing.Exit(_invocationId, _result);
          }
          return _result;
      }
  </code></pre>
  
  <p>I have a unit test to call the generated code using</p>
  
  <pre><code>var api = MakeApi();
  var task=api.GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync(req);
  var carriers  = task.Result.Body.Carriers;
  </code></pre>
  
  <p>where</p>
  
  <pre><code>    private static MyApiService MakeApi()
      {
          var setting = new MyAPISettings(false);
          var api = new MyApiService(setting);
          return api;
      }
  </code></pre>
  
  <p>and  MyApiService contains (with altered namespaces)</p>
  
  <pre><code>    public Task&lt;HttpOperationResponse&lt;GetAvailableCarriersResponse&gt;&gt; GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync(
          GetAvailableCarriersRequest request = default(GetAvailableCarriersRequest), Dictionary&lt;string, List&lt;string&gt;&gt; customHeaders = null,
          CancellationToken cancellationToken = default(CancellationToken))
      {
          return ApiCaller.ExecuteAsync(
              async headers =&gt; await API.GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync(request, headers, cancellationToken),
              async () =&gt; await GetTokenHeadersAsync(customHeaders));
      }
  </code></pre>
  
  <p>where apicaller is</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Threading.Tasks;
  
  namespace MyServices
  {
      public static class ApiCaller
      {
  
  
  
          private static Dictionary&lt;string, List&lt;string&gt;&gt; Headers { get; set; }
  
              private static string GetHeadersMessage()
              {
                  string ret = "";
  
                  if (Headers != null)
                  {
                      foreach (string key in Headers.Keys)
                      {
                          if (Headers[key] != null)
                          {
                              foreach (string value in Headers[key])
                              {
                                  ret = $"{key}-{value}\n";
                              }
                          }
                      }
                  }
  
                  return ret;
              }
  
  
          public async static Task&lt;T&gt; ExecuteAsync&lt;T&gt;(Func&lt;Dictionary&lt;string, List&lt;string&gt;&gt;, Task&lt;T&gt;&gt; f,
                  Func&lt;Task&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt;&gt; getHeaders)
              {
                  T ret = default(T);
  
                  try
                  {
                      try
                      {
                          if (getHeaders != null &amp;&amp; Headers == null)
                          {
                              Headers = await getHeaders();
                          }
  
                          ret = await f(Headers);
                      }
                      catch (Microsoft.Rest.HttpOperationException ex1)
                      {
                          if (ex1.Response?.StatusCode == System.Net.HttpStatusCode.Unauthorized &amp;&amp; getHeaders != null)
                          {
                              Headers = await getHeaders();
                              ret = await f(Headers);
                          }
                          else
                          {
                              throw;
                          }
                      }
                  }
                  catch (Exception ex)
                  {
                      //Log.Error(ex, $"... API CALL ERROR ...\nHEADERS:{GetHeadersMessage()}");
                      throw new Exception($"Error calling the API. {ex.Message}", ex);
                  }
  
                  return ret;
              }
          }
      }
  </code></pre>
  
  <p>My Api throws an InternalServerError 
  However when I run the unit test, I get an error in the client code.</p>
  
  <p>The error occurs at </p>
  
  <pre><code>        // Create Result
          var _result = new HttpOperationResponse&lt;GetAvailableCarriersResponse&gt;();
  </code></pre>
  
  <p>And is </p>
  
  <pre><code>System.Exception: Error calling the API. Operation returned an invalid status code 'InternalServerError' ---&gt; Microsoft.Rest.HttpOperationException: Operation returned an invalid status code 'InternalServerError'
     at MyConnector.MyApi.&lt;GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync&gt;d__49.MoveNext() 
  </code></pre>
  
  <p>How can I work around this?</p>
  
  <p>I note that the code for HttpOperationResponse is</p>
  
  <pre><code>namespace Microsoft.Rest
  {
    /// &lt;summary&gt;
    /// Represents the base return type of all ServiceClient REST operations.
    /// &lt;/summary&gt;
    public class HttpOperationResponse&lt;T&gt; : HttpOperationResponse, IHttpOperationResponse&lt;T&gt;, IHttpOperationResponse
    {
      /// &lt;summary&gt;Gets or sets the response object.&lt;/summary&gt;
      public T Body { get; set; }
    }
  }
  </code></pre>
  
  <p>Here is the structure for GetAvailableCarriersResponse</p>
  
  <pre><code>using Newtonsoft.Json;
  using System.Collections.Generic;
  
  public partial class GetAvailableCarriersResponse
  {
      public GetAvailableCarriersResponse()
      {
          CustomInit();
      }
  
      public GetAvailableCarriersResponse(IList&lt;DeliverBy&gt; carriers = default(IList&lt;DeliverBy&gt;))
      {
          Carriers = carriers;
          CustomInit();
      }
  
      partial void CustomInit();
  
      [JsonProperty(PropertyName = "carriers")]
      public IList&lt;DeliverBy&gt; Carriers { get; set; }
  
  }
  </code></pre>
  
  <p>[Update]</p>
  
  <p>In ApiCaller ExecuteAsync the following executes.</p>
  
  <pre><code>throw;
  </code></pre>
  
  <p>If I catch the error at this point, it's (edited) ToString() returns</p>
  
  <pre><code>"Microsoft.Rest.HttpOperationException: Operation returned an invalid status code 'InternalServerError' at MyAPI.
  
  &lt;GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync&gt;d__49.MoveNext() in 
  MyConnector\\generated\\MyAPI.cs:line 4018
  
  End of stack trace from previous location where exception was thrown at 
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
  System.Runtime.CompilerServices.TaskAwaiter.
  HandleNonSuccessAndDebuggerNotification(Task task) 
  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  at MyApiService.&lt;&gt;c__DisplayClass39_0.&lt;&lt;GetAvailableCarriersByJobHeaderIdWithHttpMessagesAsync&gt;b__0&gt;d.MoveNext() 
  in MyApiService.cs:line 339
  End of stack trace from previous location where exception was thrown  
  
  at System.Runtime.ExceptionServices.ExceptionDispatch
  Info.Throw() at System.Runtime.CompilerServices.TaskAwaiter.
  HandleNonSuccessAndDebuggerNotification(Task task)
  at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()  
  at MyServices.ApiCaller.&lt;ExecuteAsync&gt;d__5`1.MoveNext() 
  in ApiCaller.cs:line 50"
  </code></pre>
  
  <p>I edited some of the names in the above code to simplify and obfuscate.</p>
  
  <p>[Update]</p>
  
  <p>The problem seems to be to do with the getHeaders parameter to ApiCaller.ExecuteAsync</p>
  
  <p><a href="https://i.stack.imgur.com/mw72O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mw72O.png" alt="ExecuteAsync"></a></p>
  
  <p>[Update]</p>
  
  <p>If I examine ex1 thrown in ExecuteAsync, I can get my Api Error type using</p>
  
  <pre><code>ex1.Response.StatusCode
  </code></pre>
  
  <p>but how do I get the error description?</p>