【问题标题】:try/catch with CURL, Google shortener API?尝试/捕捉 CURL、Google 缩短 API?
【发布时间】:2015-03-22 20:31:57
【问题描述】:

我正在使用 Google Shortener API,需要处理错误:

https://developers.google.com/url-shortener/v1/getting_started#errors

这是我的代码:

public function shorten($url, $extended = false)
{
    # Check buffer
    if ( !$extended && !$this->extended && !empty(self::$buffer[$url]) ) {
        return self::$buffer[$url];
    }

    # Payload
    $data = array( 'longUrl' => $url );
    $data_string = '{ "longUrl": "'.$url.'" }';

    # Set cURL options
    curl_setopt($this->ch, CURLOPT_POST, count($data));
    curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, Array('Content-Type: application/json'));

    if ( $extended || $this->extended) {
        return json_decode(curl_exec($this->ch));
    } else {
        $ret = json_decode(curl_exec($this->ch))->id;
        self::$buffer[$url] = $ret;
        return $ret;
    }
}

但我不太确定如何尝试/捕获以获取 Google 返回的错误消息?

【问题讨论】:

  • 考虑更具体地说明您的问题。现在这看起来就像“这个大代码块有什么问题?”对大多数人来说。特别是哪些错误消息没有得到处理,结果会发生什么?
  • @someone-or-other 代码有效。但是 Google 一直拒绝 URL Shorten 请求,我需要打印错误消息

标签: php curl


【解决方案1】:

您有一个多维数组,因此您可以循环遍历数组,或者更简单的方法是简单地检查错误字段和代码字段是否存在

    if ( $extended || $this->extended) {
                $result = json_decode(curl_exec($this->ch));
               if(array_key_exists('errors',$result) && array_key_exists('code',$result)){
                    //handle error
                       }
                    else{
                   //do stuff
                       }

        } else {
                $ret = json_decode(curl_exec($this->ch))->id;
                self::$buffer[$url] = $ret;
                return $ret;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2010-11-23
    • 2013-08-04
    • 2014-12-27
    • 1970-01-01
    相关资源
    最近更新 更多