2015-10-22 108 views
1

我寫了一個非常簡單的WebApiClient擴展HttpClient。代碼如下。這樣做的主要原因是當httpResponse.IsSuccessStatusCode爲false時拋出MyOwnWebApiException。WebAPI客戶端 - 處理我自己的異常,然後AggregateException

public class WebApiClient : HttpClient 
{ 

    public WebApiClient(string apiBaseUrl) 
    { 
     this.BaseAddress = new Uri(apiBaseUrl); 
     this.DefaultRequestHeaders.Accept.Clear(); 

    } 

    public void AddAcceptHeaders(MediaTypeWithQualityHeaderValue header) 
    { 
     this.DefaultRequestHeaders.Accept.Add(header); 
    } 

    public async Task<string> DoPost(string endPoint, Object dataToPost) 
    { 
     HttpResponseMessage httpResponse = await ((HttpClient)this).PostAsJsonAsync(endPoint, dataToPost); 
     if (httpResponse.IsSuccessStatusCode) 
     { 
      string rawResponse = await httpResponse.Content.ReadAsStringAsync(); 
      return rawResponse; 
     } 
     else 
     { 
      string rawException = await httpResponse.Content.ReadAsStringAsync(); 
      MyOwnWebApiErrorResponse exception = 
      JsonConvert.DeserializeObject<MyOwnApiErrorResponse>(rawException, GetJsonSerializerSettings()); 

      throw new MyOwnWebApiException (exception.StatusCode,exception.Message,exception.DeveloperMessage,exception.HelpLink); 
     } 
    } 


    #region "Private Methods" 

    private static JsonSerializerSettings GetJsonSerializerSettings() 
    { 
     // Serializer Settings 
     var settings = new JsonSerializerSettings() 
     { 
      TypeNameHandling = TypeNameHandling.All, 
      ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, 
      ObjectCreationHandling = ObjectCreationHandling.Auto 
     }; 
     return settings; 
    } 

    #endregion 

以下是使用WebApiClient的類的代碼。

class TestWebApiClient 
{ 
    private WebApiClient _client; 
    public ComputationProcessesWebApiClient() 
    { 
     _client = new WebApiClient("http://test.api/"); 
     _client.AddAcceptHeaders(new MediaTypeWithQualityHeaderValue("application/json")); 

    } 

    public void GetData(string dataFor) 
    { 
     try 
     { 
      DataRequest request = new DataRequest(); 
      request.dataFor = dataFor; 

      **// THIS LINE IS THROWING AGGREGATEEXCEPTION--- **I WANT MyOwnException **** 
      string response = _client.DoPost("GetData", request).Result; // Use the End Point here .... 

     } 
     catch (MyOwnWebApiException exception) 
     { 
      //Handle exception here 
     } 
    } 

} 

問題 在TestWebApiClient類,我不想趕AggregateException,而我想保持它更高貴和捕捉MyOwnWebApiException,但問題是行** _client.DoPost(「的GetData」 ,request).Result **拋出一個AggregateException,如果WebApi發生錯誤。如何更改代碼,以便從TestWebApiClient我只需要捕捉MyOwnException?

回答

1

這是由於同步等待您的任務。如果你保持異步並等待你的任務,你會發現你的實際異常是被捕獲的異常。

比較下面的以下內容:

void Main() 
{ 
    TryCatch(); 
    TryCatchAsync(); 
} 
void TryCatch() 
{ 
    try 
    { 
     ThrowAnError().Wait(); 
    } 
    catch(Exception ex) 
    { 
     //AggregateException 
     Console.WriteLine(ex); 
    } 
} 
async Task TryCatchAsync() 
{ 
    try 
    { 
     await ThrowAnError(); 
    } 
    catch(Exception ex) 
    { 
     //MyException 
     Console.WriteLine(ex); 
    } 
} 
async Task ThrowAnError() 
{ 
    await Task.Yield(); 
    throw new MyException(); 
} 
public class MyException:Exception{}; 

前提示爲異步/ AWAIT?它是異步/等待一直下降。當你.Wait().ResultTask,事情開始變得混亂。

+0

非常感謝。這意味着如果我必須調用.Wait()或.Result(),否則我將不得不捕獲AggregateException,如果我只是用我的調用DoPost等待keywork,那麼我應該能夠直接捕獲MyOwnWebApiException。我試過了,它工作。 – ATHER

相關問題