user1251698
user1251698

Reputation: 2143

How to catch error in JSON response?

I'm getting the json data from the twitter using the wordpress function wp_remote_get as below:

$response = wp_remote_get('http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter');
$json = json_decode($response['body']);

and it works fine. However, it totally creates the problem on my page if the twitter returns some error. In that case the content on my page does not load after that error part. So how can I catch the error and continue, only if there is no error.

For example if the twitter limit exceeds, it returns following response:

{"request":"\/1\/statuses\/user_timeline.json?screen_name=twitter","error":"Rate limit exceeded. Clients may not make more than 150 requests per hour."}

From the above responsive, how can i get the error. I'm trying following, but it does not work (my page does not load at all)

if (!isset($json['error']){
    //continue
}

Upvotes: 1

Views: 1878

Answers (2)

Sacx
Sacx

Reputation: 6392

You need to use json_decode to "transform" your "json string" in an object.

$j = json_decode($json);
echo $j->{'error'}

Here you will find everything what you need to know about json_decode: http://php.net/manual/en/function.json-decode.php

Upvotes: 1

MrCode
MrCode

Reputation: 64526

It doesn't work because you are trying to access $json as an array, which it is not. It's an object, so use:

if (!isset($json->error){
    //continue
}

Your page doesn't load because it's causing a fatal error, which in turn produces a 500 internal server error. If you check your error log you'll find:

Fatal error: Cannot use object of type stdClass as array in ....

Upvotes: 7

Related Questions