我使用的是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收回Google返回的错误消息?
答案 0 :(得分: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;
}