我有以下代码
public async Task<T> SendData<T>()
{
T result = default(T);
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
try
{
foreach (var p in ParametresToSend)
formData.Add(p.Value, p.Key);
HttpResponseMessage response = await client.PostAsync(URL, formData);
string stringContent = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(stringContent);
}
catch (Exception ex)
{
throw ex;
}
finally
{
ParametresToSend.Clear();
}
}
}
return result;
}
它工作正常,但是如果检查可用性后(如果很短的时间,但有可能)互联网不可用,则会捕获 first HttpRequestException。在此之后,将立即抛出 second HttpRequestException,但是catch块无法捕获它,并且应用程序崩溃。为什么令人开心?
答案 0 :(得分:0)
您在捕获异常时会重新抛出该异常,这与不首先捕获该异常一样好。
您的应用程序崩溃是因为没有任何地方可以处理此重新抛出的异常-您没有任何全局异常处理,如果这本身就是一个ASP.NET应用程序,则是个好主意
答案 1 :(得分:-1)
try
{
HttpResponseMessage response = await client.PostAsync(URL, formData);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string stringContent = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(stringContent);
}
}
catch (HttpRequestException)
{
throw;
}
尝试