1

I have this code:

public static string Connect(string Uri)
{
    try
    {
        HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
        connection.Method = "GET";
        string response;

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)    
        using (var responseStream = new StreamReader(response.GetResponseStream()))
        {
            responseText = responseStream.ReadToEnd();
        }

        return response;
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

If the API return 200 http status the response variable is returned correctly, instead if I have client error 400 or 500 the code fall in exception. I want manage this exception in the try instead fall in the Console.WriteLine, there is a change for do this?

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Sevengames Xoom
  • 312
  • 1
  • 6
  • 18
  • Some answers here: http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba – Blorgbeard Mar 01 '16 at 20:28
  • @Blorgbeard so i can't manage the exception in the try? Only in the catch? This is so bad. – Sevengames Xoom Mar 01 '16 at 20:36
  • That's generally the point of try/catch. It's how exception handling works in C#. It's just unfortunate that `GetReponse()` throws an exception for HTTP error codes, when they are often not really an "exceptional" occurrence. – Blorgbeard Mar 01 '16 at 20:40
  • @Blorgbeard uhm ok, I will manage into the `catch` block. – Sevengames Xoom Mar 01 '16 at 20:46

1 Answers1

0

You could do something like this, to minimise duplicated code and handle the exception as close to where it's thrown as possible.

public static string Connect(string Uri)
{
   HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
    connection.Method = "GET";
    string response;

    HttpWebResponse response = null;
    try
    {
        response = request.GetResponse() as HttpWebResponse
    }
    catch (WebException ex)
    {
        response = ex.Response;
    }

    using (response)    
    using (var responseStream = new StreamReader(response.GetResponseStream()))
    {
        responseText = responseStream.ReadToEnd();
    }

    return response;
}    
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272