如何正确捕获C#的HttpClient GetAsync的异常,因此错误所说的不仅仅是“一个或多个错误发生”



以下是使用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中,并且会像以前一样将其投入。

由于您在任务上调用 .Result,因此将在捕获的异常的 InnerException属性中保留原始异常。您可以通过以下构造访问它:

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

不确定是否适用但您是否尝试过?:console.writeline(ex.getBaseexception()。tostring()。stacktrace)

相关内容