Nicholas DiPiazza
Nicholas DiPiazza

Reputation: 10585

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

The following is some code that downloads a file using 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);
}

Sometimes I call this and a file fails to download. In that situation, the catch is called but doesn't contain any information of the issue:

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)

How can I get it to the cause of this exception?

Upvotes: 4

Views: 11003

Answers (3)

Tomas Hesse
Tomas Hesse

Reputation: 395

Not really sure if this applies but have you tried?: Console.WriteLine(ex.GetBaseException().ToString().StackTrace)

Upvotes: 0

Evk
Evk

Reputation: 101453

Task.Result throws AggregateException, so you can catch that. All exceptions will be inside InnerExceptions property of that exception (there can be multiple in theory, but in your case there will be just one). First of those exceptions (or the only one if there is just one) is also in InnerException property.

If you don't want to dig inside AggregateException, use .GetAwaiter().GetResult() instead of .Result - this will not wrap exception into AggregateException and will throw it as is.

Upvotes: 4

CodeFuller
CodeFuller

Reputation: 31282

Since you're calling .Result on the task, original exception will be held in InnerException property of catched exception. You could access it with following construct:

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

Upvotes: 2

Related Questions