【发布时间】:2013-02-01 12:13:01
【问题描述】:
在使用 C# 和 .NET 4.5 出现 404 错误的情况下,我正在尝试确定 HttpClient 的 GetAsync 方法返回的 response。
目前我只能判断发生了错误,而不是错误的状态,例如 404 或超时。
目前我的代码我的代码如下所示:
static void Main(string[] args)
{
dotest("http://error.123");
Console.ReadLine();
}
static async void dotest(string url)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception e)
{
// .. and understanding the error here
Console.WriteLine( e.ToString() );
}
}
我的问题是我无法处理异常并确定其状态和其他问题的详细信息。
我将如何正确处理异常并解释发生了什么错误?
【问题讨论】:
-
msdn.microsoft.com/en-us/library/system.exception.aspx 看看属性。如果需要打印消息,可以使用
e.Message。不确定,你想做什么。
标签: c# exception-handling httpclient .net-4.5 async-await