facebook-csharp-sdk/http-helper

don't throw WebExceptionWrapper when opening read stream

prabirshrestha opened this issue · 1 comments

currently HttpHelper behaves exactly like HttpWebRequest in the sense, it will throw WebExceptionWrapper if the status code is not 200ok.

So we need to catch the exception and handle it correctly like below. It gets more complicated for async codes.

var httpHelper = new HttpHelper("https://graph.facebook.com/me");
string responseString = null;

try
{
    using (var stream = httpHelper.OpenRead())
    {
        using (var reader = new StreamReader(stream))
        {
            responseString = reader.ReadToEnd();
        }
    }
}
catch (WebExceptionWrapper ex)
{
    if (ex.GetResponse() == null)
        throw;
    else
    {
        using (var stream = httpHelper.OpenRead())
        {
            using (var reader = new StreamReader(stream))
            {
                responseString = reader.ReadToEnd();
            }
        }
    }
}

dynamic result = SimpleJson.DeserializeObject(responseString);
Console.WriteLine(result);

It should be this instead. User can access the original exception by getting httpHelper.InnerException. (InnerException already exists in the current version of HttpHelper.)

var httpHelper = new HttpHelper("https://graph.facebook.com/me");
string responseString = null;

using(var stream = httpHelper.OpenRead())
{
    var response = httpHelper.HttpWebResponse;
    if(response == null) throw httpHelper.InnerException;

    var statusCode = response.StatusCode;
    using(var reader = new StreamReader())
    {
        responseString = reader.ReadToEnd();
    }
}

dynamic result = SimpleJson.DeserializeObject(responseString);
Console.WriteLine(result);

updated in v0.10.0-alpha

private async void Async()
{
    var httpHelper = new HttpHelper("https://graph.facebook.com/4");
    var request = httpHelper.HttpWebRequest;
    request.Headers["If-None-Match"] = "\"539feb8aee5c3d20a2ebacd02db380b27243b255\"";

    try
    {
        using (var stream = await httpHelper.OpenReadTaskAsync())
        {
            var response = httpHelper.HttpWebResponse;
            var innerException = httpHelper.InnerException;
            var statusCode = response.StatusCode;

            using (var reader = new StreamReader(stream))
            {
                var str = await reader.ReadToEndAsync();
            }
        }
    }
    catch(WebExceptionWrapper ex)
    {
        throw;
    }
}

Now when opening the response stream, it will only throw exception if stream is null. for non 200ok status code it will continue to execute normally, you can get the original exception using httpHelper.InnerException.