php是怎么处理异常的?像下面这样的代码,如何得知是执行成功了还是失败了?
public function get_user($ch, $apikey) { \think\log::record('into get_user...'); curl_setopt($ch, curlopt_url, 'https://sms.xxx.com/v2/user/get.json'); curl_setopt($ch, curlopt_postfields, http_build_query(array('apikey' => $apikey))); $response = curl_exec($ch); \think\log::record('$response : '.$response); if (false === $response) { die(curl_error); } return $response; }
回复内容: php是怎么处理异常的?像下面这样的代码,如何得知是执行成功了还是失败了?
public function get_user($ch, $apikey) { \think\log::record('into get_user...'); curl_setopt($ch, curlopt_url, 'https://sms.xxx.com/v2/user/get.json'); curl_setopt($ch, curlopt_postfields, http_build_query(array('apikey' => $apikey))); $response = curl_exec($ch); \think\log::record('$response : '.$response); if (false === $response) { die(curl_error); } return $response; }
$apikey = '';$ch = curl_init();curl_setopt($ch, curlopt_url, 'https://sms.yunpian.com/v2/user/get.json');curl_setopt($ch, curlopt_postfields, http_build_query(array('apikey' => $apikey)));curl_setopt($ch, curlopt_ssl_verifypeer, false);curl_setopt($ch, curlopt_ssl_verifyhost, 1);$response = curl_exec($ch);if (false === $response) { die(curl_error($ch));}print_r($response);
自己运行调试吧,不解释了。
抛出异常 throw new exception()
可能触发异常的代码 try{...}
捕获异常 catch(exception $e){}
补充:
protected function curl($url, $postfields = null){$ch = curl_init();curl_setopt($ch, curlopt_url, $url);curl_setopt($ch, curlopt_useragent, 'mozilla/5.0 (compatible; msie 5.01; windows nt 5.1)');curl_setopt($ch, curlopt_header, 0);curl_setopt($ch, curlopt_failonerror, 0);curl_setopt($ch, curlopt_returntransfer, 1);//curl_setopt($ch,curlopt_httpheader,array('expect:'));if (is_array($postfields) && 0 $v){if('@' != substr($v, 0, 1))//判断是不是文件上传{$postbodystring .= '$k=' . urlencode($v) . '&';}else//文件上传用multipart/form-data,否则用www-form-urlencoded{$postmultipart = true;}}unset($k, $v);curl_setopt($ch, curlopt_post, 1);if ($postmultipart){cur l_setopt($ch, curlopt_postfields, $postfields);}else{//var_dump($postbodystring);curl_setopt($ch, curlopt_postfields, substr($postbodystring,0,-1));}}$reponse = curl_exec($ch);//return curl_getinfo($ch);if (curl_errno($ch)){throw new exception(curl_error($ch),0);}else{$httpstatuscode = curl_getinfo($ch, curlinfo_http_code);if (200 !== $httpstatuscode){throw new exception($reponse,$httpstatuscode);}}curl_close($ch);return $reponse;}
补充 @incnick 的答案,php 7 版本,异常 多了异常类 error ,跟 exception 是平级关系
可以参考
1、http://php.net/manual/zh/migration70.incompatible.php
2、http://php.net/manual/zh/language.errors.php7.php
在一个项目里面, 你很难保证curl发出的http请求一定是正确并且在超时范围内返回的..反而是经常出问题的.
所以为了项目后面的代码能正确处理curl遇到的错误, 我认为抛出异常是最好的方式.
$response = curl_exec($ch);if (false === $response) { die(curl_error($ch)); throw new exception(curl_error($ch),curl_errno($ch));}
php 也有try catch throw吧