如何捕获JSON响应中的错误?

use*_*698 1 php api twitter wordpress json

我使用wordpress函数wp_remote_get从twitter获取json数据,如下所示:

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

它工作正常.但是,如果twitter返回一些错误,它会在我的页面上完全产生问题.在这种情况下,我的页面上的内容不会在该错误部分后加载.那么,只有在没有错误的情况下,我怎样才能捕获错误并继续.

例如,如果推特限制超过,则返回以下响应:

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

从上面的响应,我怎么能得到错误.我正在尝试关注,但它不起作用(我的页面根本没有加载)

if (!isset($json['error']){
    //continue
}
Run Code Online (Sandbox Code Playgroud)

MrC*_*ode 6

它不起作用,因为您尝试以$json数组形式访问,而不是.这是一个对象,所以使用:

if (!isset($json->error){
    //continue
}
Run Code Online (Sandbox Code Playgroud)

您的页面未加载,因为它导致致命错误,从而产生500内部服务器错误.如果您检查错误日志,您会发现:

致命错误:不能使用stdClass类型的对象作为数组....