Which exceptions can HttpClient throw?

C#Httpclient

C# Problem Overview


I am using HttpClient in a xamarin forms project

The class is documented, but I can not find any documentation about which exceptions its methods might throw.

For example the GetAsync Method does not have any documentation about possible exceptions. But I assume it throws, for example when the server is unreachable.

Is there somewhere a list of exceptions this class might throw?

C# Solutions


Solution 1 - C#

As others have commented it depend on what you are calling with HttpClient. I get what you meant though and so here are some exceptions thrown with typical method calls.

SendAsync can throw:

  • ArgumentNullException The request was null.
  • InvalidOperationException The request message was already sent by the HttpClient instance.
  • HttpRequestException The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout.
  • TaskCanceledException The request timed-out or the user canceled the request's Task.

Source: Microsoft Docs -> HttpClient -> SendAsync

Similarly GetAsync PostAsync PutAsync GetStringAsync GetStreamAsync etc can throw ArgumentNullException, HttpRequestException and as above (but not InvalidOperationException).

Source: Microsoft Docs -> HttpClient -> GetAsync

Once you have called SendAsync or GetAsync etc you will have a Task<HttpResponseMessage>. Once awaited I tend to call EnsureSuccessStatusCode() to throw a HttpRequestException if there is a non success HTTP status code returned. https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs#L161

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNathanView Question on Stackoverflow
Solution 1 - C#BritishDeveloperView Answer on Stackoverflow