如何正确捕获来自 C# 的 HttpClient getAsync 的异常,以便错误显示超过 "One or more errors occurred"?

How to properly catch exceptions from C#'s HttpClient getAsync so the error says more than "One or more errors occurred"?

以下是一些使用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)

如何找到导致此异常的原因?

由于您在任务上调用 .Result,原始异常将保存在已捕获异常的 InnerException 属性 中。您可以使用以下结构访问它:

string message = e?.InnerException.Message ?? e.Message;

Task.Result 抛出 AggregateException,所以你可以抓住它。所有异常都将在该异常的 InnerExceptions 属性 内(理论上可以有多个,但在您的情况下只有一个)。第一个例外(如果只有一个例外,则为唯一例外)也在 InnerException 属性.

如果您不想深入 AggregateException,请使用 .GetAwaiter().GetResult() 而不是 .Result - 这不会将异常包装到 AggregateException 中并将其抛出是。

不确定这是否适用,但您尝试过吗?:Console.WriteLine(ex.GetBaseException().ToString().StackTrace)