2015-10-22 105 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

相关问题