WebAPI客户端 - 处理我自己的异常而不是AggregateException

时间:2015-10-22 17:16:43

标签: c# asp.net-web-api asp.net-web-api2

我编写了一个非常简单的WebApiClient,扩展了HttpClient。代码如下。这样做的主要原因是当httpResponse.IsSuccessStatusCode为false时抛出MyOwnWebApiException。

 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 个答案:

答案 0 :(得分: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{};

async / await的顶级提示?这是异步/等待一直向下。在.Wait().ResultTask时,事情开始变得混乱。