Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine a 404 response status when using the HttpClient.GetAsync()

I am trying to determine the response returned by HttpClient's GetAsync method in the case of 404 errors using C# and .NET 4.5.

At present I can only tell that an error has occurred rather than the error's status such as 404 or timeout.

Currently my code my code looks like this:

    static void Main(string[] args)     {         dotest("http://error.123");         Console.ReadLine();     }      static async void dotest(string url)     {         HttpClient client = new HttpClient();          HttpResponseMessage response = new HttpResponseMessage();          try         {             response = await client.GetAsync(url);              if (response.IsSuccessStatusCode)             {                 Console.WriteLine(response.StatusCode.ToString());             }             else             {                 // problems handling here                 string msg = response.IsSuccessStatusCode.ToString();                  throw new Exception(msg);             }          }         catch (Exception e)         {             // .. and understanding the error here             Console.WriteLine(  e.ToString()  );                         }     } 

My problem is that I am unable to handle the exception and determine its status and other details of what went wrong.

How would I properly handle the exception and interpret what errors occurred?

like image 207
Gga Avatar asked Feb 01 '13 12:02

Gga


People also ask

What does HttpClient GetAsync return?

The HTTP request is sent out, and HttpClient. GetAsync returns an uncompleted Task .

What is HttpClient GetAsync?

GetAsync(Uri, HttpCompletionOption) Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. GetAsync(Uri, CancellationToken) Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.


2 Answers

The property response.StatusCode is a HttpStatusCode enum.

This is the code I use to get a friedly name

if (response != null) {     int numericStatusCode = (int)response.StatusCode;      // like: 503 (ServiceUnavailable)     string friendlyStatusCode = $"{ numericStatusCode } ({ response.StatusCode })";      // ...  } 

Or when only errors should be reported

if (response != null) {     int statusCode = (int)response.StatusCode;      // 1xx-3xx are no real errors, while 3xx may indicate a miss configuration;      // 9xx are not common but sometimes used for internal purposes     // so probably it is not wanted to show them to the user     bool errorOccured = (statusCode >= 400);     string friendlyStatusCode = "";      if(errorOccured == true)     {         friendlyStatusCode = $"{ statusCode } ({ response.StatusCode })";     }          // .... } 
like image 45
marsh-wiggle Avatar answered Sep 28 '22 04:09

marsh-wiggle


You could simply check the StatusCode property of the response:

static async void dotest(string url) {     using (HttpClient client = new HttpClient())     {         HttpResponseMessage response = await client.GetAsync(url);          if (response.IsSuccessStatusCode)         {             Console.WriteLine(response.StatusCode.ToString());         }         else         {             // problems handling here             Console.WriteLine(                 "Error occurred, the status code is: {0}",                  response.StatusCode             );         }     } } 
like image 87
Darin Dimitrov Avatar answered Sep 28 '22 05:09

Darin Dimitrov