Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which exceptions can HttpClient throw?

Tags:

c#

httpclient

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?

like image 888
Nathan Avatar asked Nov 18 '16 12:11

Nathan


People also ask

How do you perform error handling in HttpClient?

The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.

How do I use HttpClient Getasync?

Using SendAsync, we can write the code as: static async Task SendURI(Uri u, HttpContent c) { var response = string. Empty; using (var client = new HttpClient()) { HttpRequestMessage request = new HttpRequestMessage { Method = HttpMethod. Post, RequestUri = u, Content = c }; HttpResponseMessage result = await client.


1 Answers

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

like image 99
BritishDeveloper Avatar answered Sep 17 '22 18:09

BritishDeveloper