HttpClient - 处理聚合异常 [英] HttpClient - dealing with aggregate exceptions

查看:205
本文介绍了HttpClient - 处理聚合异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用与以下类似的HttpClient:

Hi i am using HttpClient similar to this:

public static Task<string> AsyncStringRequest(string url, string contentType)
{
    try
    {
        var client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(contentType));

        return client.GetStringAsync(url).ContinueWith(task => {
            return task.Result;
        });
    }
    catch (AggregateException ex)
    {
        throw ex;
    }
    catch (WebException ex)
    {
        throw ex;
    }       
    catch (Exception ex)
    {
        throw ex;
    }
}

但我在处理异常时遇到困难。我添加了额外的catch块,只是尝试和分步抛出,但是没有一个断点被捕获在任何catch块中。我意识到使用Task可能会在与调用者不同的线程上发生异常,因此异常被包装在一个聚合容器中,但我不知道处理这些异常的最佳方法是。

But i am having difficulties dealing with exceptions. I have added the additional catch blocks just to try and step throw, but none of the break points are caught in any of the catch blocks. I realise using Task the exception could occur on a different thread than the caller so the exception is wrapped in a aggregate container, but i am not sure what the best way to deal with these exceptions is.

例如,我在请求中向Web服务请求并指定了无效参数,并抛出异常。我想让我能够捕获总体异常,并查看内部意见,找出为什么请求失败并返回友好的消息。

For example i make a request to a web service and specific an invalid parameter in the request, and an exception is thrown. I want to me able to catch the aggregate exceptions and look at the innerexceptions to work out why the request has failed and return a friendly message.

所以我的问题是,什么是捕获这些聚合异常并处理它们的最好方法?

So my question is, what is the best way to catch these aggregate exceptions and deal with them?

推荐答案

异常是由 task.Result

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url).ContinueWith(task =>
{
    try
    {
        return task.Result;
    }
    catch (AggregateException ex)
    {
        throw ex;
    }
    catch (WebException ex)
    {
        throw ex;
    }       
    catch (Exception ex)
    {
        throw ex;
    }
});

更好:检查任务 faulted ,然后再访问 task.Result

Better: check if the task faulted before accessing task.Result:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url).ContinueWith(task =>
{
    if (task.IsFaulted)
    {
        var ex = task.Exception;
    }
    else if (task.IsCancelled)
    {
    }
    else
    {
        return task.Result;
    }
});

如果您没有在 ContinueWith ,您可以直接省略:

If you're not actually doing something in the ContinueWith, you can simply omit it:

var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url);

这篇关于HttpClient - 处理聚合异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆