How do I handle Facebook responses correctly?

I am using the standard API provided by Facebook. A response looks something like the following for an unsuccessful transaction

{
  "error": {
    "message": "Error validating access token: Session has expired at unix 
                time SOME_TIME. The current unix time is SOME_TIME.", 
    "type": "OAuthException", 
    "code": 190
    "error_subcode": 463
}

and a succesful one ssomething like

{"id":"100054544144330556_25940175479504"}

How do I detect a successful transaction? do I have to parse and see if it contains the word "error" or is there a better way?

Answers


Facebook SDK will throw an error if finds 'error' in the result. If you are using standard API, then you have to do the same.

For example, in Facebook PHP SDK you can see this (In a easy readable way, this is not 100% PHP):

if (isset('error')) {
    throwAPIException();
}

Just do the same. But don't forget to parse JSON object before, don't search as a string, search as a key->value pair if there's an 'error' key.


There are lots of libraries out there to assist you with the REST calls to the FaceBook API. Have you looked into RestFB? I assume this would be of value to you as you are developing for Android.

With this framework you can abstract yourself from the individual response elements and deal with what really matters...the objects themselves (Users, Comments, etc).

Utilizing this framework you could do something like the following:

FacebookEngine faceBookEngine = new DefaultFacebookClient(authToken);
User facebookUser = facebookClient.fetchObject("me", User.class);

if (facebookUser == null)
    {
        throw new FacebookOAuthException("Bad user data",
                        "user is null!");
    }

In Android, the most direct and simple way is to check for "id":

...
JSONObject jason = new JSONObject(jsonString);
...

try{
    String id = jason.getString("id");
} catch(JSONException je) {
    //ID was not found
    ....
}

Need Your Help

How to fetch the document mode of Internet Explorer in JAVA

java javascript internet-explorer

I am trying to fetch the document mode of the browser i.e IE from the given function.I knew that in javascript we can use document.documentMode to fetch the doucment mode of IE. But is there any wa...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.