以下是代码:
protected static async Task httpPost(String url, String data)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseURL);
AuthenticationManager.SetHeadersForCommunication(client);
HttpResponseMessage response = await client.PostAsync(url, new StringContent(data, Encoding.UTF8, "application/json"));
String result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
Console.WriteLine(result);
}
else
{
throw new SystemException(
"Failed : HTTP error code : " + response.StatusCode
+ "\nReason:" + result.ToString()
);
}
}
}
当response.IsSuccessStatusCode为true时,我在控制台上得到结果,即可。 但如果不是,则不会处理任何异常,并且方法会像冻结一样。
答案 0 :(得分:0)
您在异步方法中抛出异常但可能无法正确处理它。请尝试遵循以下模式:
Task myWork = null;
try
{
myWork = httpPost(url, data);
await myWork;
}
catch(SystemException e)
{
//now you can get at the exception in myWork.Exception
}
由于嵌套的异步调用,该集合将存储任何嵌套异常。请参阅Exception属性的文档,该属性返回聚合异常。