Which exceptions can HttpClient throw?
Solution 1:
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