Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process WebResponse when .NET throws WebException ((400) Bad Request)?

I'm using Facebook Graph Api and trying to get user data. I'm sending user access token and in case this token is expired or invalid Facebook returns status code 400 and this response:

{
    "error": {
        "message": "Error validating access token: The session is invalid because the user logged out.",
        "type": "OAuthException"
    }
}

The problem is that when I use this C# code:

try {
   webResponse = webRequest.GetResponse(); // in case of status code 400 .NET throws WebException here
} catch (WebException ex) {
}

If status code is 400 .NET throws WebException and my webResponse is null after exception is caught so I have no chance to process it. I want to do it to make sure that the problem is in expired token and not somewhere else.

Is there a way to do it?

Thanks.

like image 751
Burjua Avatar asked Sep 30 '11 10:09

Burjua


2 Answers

Using a try/catch block like this and processing the error message appropriately should work fine:

    var request = (HttpWebRequest)WebRequest.Create(address);
    try {
        using (var response = request.GetResponse() as HttpWebResponse) {
            if (request.HaveResponse && response != null) {
                using (var reader = new StreamReader(response.GetResponseStream())) {
                    string result = reader.ReadToEnd();
                }
            }
        }
    }
    catch (WebException wex) {
        if (wex.Response != null) {
            using (var errorResponse = (HttpWebResponse)wex.Response) {
                using (var reader = new StreamReader(errorResponse.GetResponseStream())) {
                    string error = reader.ReadToEnd();
                    //TODO: use JSON.net to parse this string and look at the error message
                }
            }
        }
    }
}

However, using the Facebook C# SDK makes this all really easy so that you don't have to process this yourself.

like image 149
bkaid Avatar answered Nov 02 '22 19:11

bkaid


The WebException still has the "real" response in the Response property (assuming there was a response at all) so you can get the data from that within the catch block.

like image 14
Jon Skeet Avatar answered Nov 02 '22 19:11

Jon Skeet