35

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Gga
  • 4,311
  • 14
  • 39
  • 74
  • http://msdn.microsoft.com/en-us/library/system.exception.aspx take a look at properties. If you need to print message, you can use `e.Message`. Not sure, what you're trying to do. – Leri Feb 01 '13 at 12:17

2 Answers2

59

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
            );
        }
    }
}
Richard Garside
  • 87,839
  • 11
  • 80
  • 93
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This gives me "A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.dll but was not handled in user code". Would you know what I might be missing? I loaded the HttpClient resource via nuget if that changes anything as it wasn't appearing by default in my .Net 4.5. – Gga Feb 01 '13 at 12:20
  • 3
    What's the exception? Is it a timeout? If so you will have to handle this case with a try/catch block. As far as server status codes are concerned, you could handle them as shown in my answer. – Darin Dimitrov Feb 01 '13 at 12:23
  • "Additional information: An error occurred while sending the request." is the only other piece of information from output window. Is that what you refer to? – Gga Feb 01 '13 at 12:24
  • Is there an InnerException? What's the type of the Exception? – Darin Dimitrov Feb 01 '13 at 12:25
  • Thank you, yes the error was a timeout in that case and your code handled a separate 404 scenario very well. Try Catch was the solution to the timeout issue. cheers – Gga Feb 01 '13 at 12:37
  • If you just want some exception for the case of a non-success status code I found response.EnsureSuccessStatusCode() was what I was looking for. – KrisG Jan 23 '20 at 13:32
1

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 })";
    }
    
    // ....
}
marsh-wiggle
  • 2,508
  • 3
  • 35
  • 52