c# - 如何正确捕获来自 C#'s HttpClient getAsync so the error says more than "发生一个或多个错误的异常?

标签 c# exception-handling dotnet-httpclient

下面是一些使用 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/

相关文章:

c# - 将全局转换器应用于 Json.NET

javascript - 异步 node.js 调用中的错误处理

c# - HttpClient FormUrlEncodedContent 编码

.net - 为什么HttpClient.PostAsync和PutAsync会处理内容?

c# - 更改传递给虚拟方法的类型

c# - 从 Windows 资源管理器拖放到我的应用程序的文本框中

c# - 调用 ReplaceDocumentAsync 方法失败返回

java - Java 默认声明 "throws Exception"吗?

c# - 如果捕获所有异常,是否需要在 try catch block 中使用 finally?

.net - 负载测试期间套接字异常