C# HttpClient - 处理聚合异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11239537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpClient - dealing with aggregate exceptions
提问by gdp
Hi i am using HttpClient similar to this:
嗨,我正在使用与此类似的 HttpClient:
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;
}
}
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.
但是我在处理异常时遇到了困难。我添加了额外的 catch 块只是为了尝试和单步抛出,但是在任何 catch 块中都没有捕获任何断点。我意识到使用 Task 异常可能发生在与调用者不同的线程上,因此异常被包装在聚合容器中,但我不确定处理这些异常的最佳方法是什么。
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.
例如,我向 Web 服务发出请求并在请求中指定一个无效参数,然后抛出异常。我希望我能够捕获聚合异常并查看内部异常以找出请求失败的原因并返回一条友好的消息。
So my question is, what is the best way to catch these aggregate exceptions and deal with them?
所以我的问题是,捕获这些聚合异常并处理它们的最佳方法是什么?
采纳答案by dtb
The exception is thrown by task.Result:
抛出异常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;
}
});
Better: check if the task faultedbefore accessing task.Result:
更好:在访问之前检查任务是否出错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;
}
});
If you're not actually doing something in the ContinueWith, you can simply omit it:
如果您实际上没有在 中做某事,则ContinueWith可以简单地省略它:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(...);
return client.GetStringAsync(url);

