下面是一些使用 System.Net.Http.HttpClient
下载文件的代码
try
{
var responseResult = new System.Net.Http.HttpClient().GetAsync(fileUrl);
using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
{
using (var fileStream = File.Create(saveToPath))
{
memStream.CopyTo(fileStream);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
有时我调用它并且文件下载失败。在这种情况下,捕获被调用但不包含问题的任何信息:
One or more errors occurred.
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at SpPrefetchIndexBuilder.FileDownloader.StartDownloads(Int32 timeout)
如何找到导致此异常的原因?
最佳答案
Task.Result
抛出 AggregateException
,因此您可以捕获它。所有异常都将在该异常的 InnerExceptions
属性内(理论上可以有多个,但在您的情况下只有一个)。第一个异常(如果只有一个,则为唯一的异常)也在 InnerException
属性中。
如果您不想深入了解 AggregateException
,请使用 .GetAwaiter().GetResult()
而不是 .Result
- 这不会将异常包装到 AggregateException
中并按原样抛出它。
关于c# - 如何正确捕获来自 C#'s HttpClient getAsync so the error says more than "发生一个或多个错误的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47677120/