douweida2878 2012-11-27 08:00
浏览 190
已采纳

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

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
}
  • 写回答

2条回答 默认 最新

  • douwen5951 2012-11-27 08:05
    关注

    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 ....

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题