【问题标题】:Catch Guzzle Exception and return string捕获 Guzzle 异常并返回字符串
【发布时间】:2022-01-31 01:38:30
【问题描述】:

所以我需要一些帮助来构建我的一种使用 ID 检索 Twitter 列表的方法。下面,我将描述并详细介绍它返回的内容。

代码

    public static function get_list($list_id)
    {
        $lists = self::get_lists();
        $params = [
            'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
            'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
        ];
        try {
            $list = $lists->get($list_id, $params);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            return $e;
        }

        return $list;
    }

$lists->get()出现问题时,会抛出以下object(GuzzleHttp\Exception\ClientException)#1640 (10) { ["request":"GuzzleHttp\Exception\RequestException":private]=>错误。

我想要实现的目标
返回 $e 以便我可以读取错误(无法使其正常工作)。

如果我将return $e 切换为return 'Hello',我仍然会看到对象而不是字符串。

IDE 建议它@throws GuzzleException

在我处理异常的方式以及为什么我无法正确返回异常错误方面,是否有人认为有什么问题?

【问题讨论】:

    标签: php guzzle


    【解决方案1】:

    尝试使用异常层次结构来捕获任何异常。 ClientException 仅捕获 400x-499 之间的状态代码。要捕获其他异常或在同一异常中捕获,您可以使用RequestException

    public static function get_list($list_id)
        {
            $lists = self::get_lists();
            $params = [
                'list.fields' => 'created_at,follower_count,member_count,private,description,owner_id',
                'user.fields' => 'created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld'
            ];
            try {
                $list = $lists->get($list_id, $params);
                if($list->getStatusCode() == 200)){
                    $return_list = json_decode($list->getBody(),true);
                }
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $error['error'] = $e->getMessage();
                $error['request'] = $e->getRequest();
                if($e->hasResponse()){
                  // you can pass a specific status code to catch a particular error here I have catched 400 Bad Request. 
                  if ($e->getResponse()->getStatusCode() == '400'){
                     $error['response'] = $e->getResponse(); 
                  }
                }
                return $error;
            } catch(\GuzzleHttp\Exception\RequestException $se){
                $error['error'] = $e->getMessage();
                $error['request'] = $e->getRequest();
                return $error;
            } catch(Exception $e){
               //other errors 
            }
    
            return $list;
        }
    

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 2016-10-31
      • 2021-08-25
      • 1970-01-01
      • 2017-03-27
      • 2019-05-02
      • 1970-01-01
      • 2020-10-23
      • 2020-11-07
      相关资源
      最近更新 更多