我已经看过文档和几个教程。但是,我无法让我的代码处理错误。我只想打印“错误。”,无论错误是什么。
这是我的代码没有处理错误,
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$page = get_data('http://....');
$doc = new DOMDocument();
@$doc->loadHTML($page);
echo $doc->saveHTML();
编辑:下一个打印出默认错误消息,但不是我的。
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($data === FALSE) {
$msg = curl_error($ch);
curl_close($ch);
throw new Exception($msg);
}
curl_close($ch);
return $data;
}
try {
$page = get_data('wrong-url');
$doc = new DOMDocument();
@$doc->loadHTML($page);
$div = $doc->getElementById('cuerpo');
echo $doc->saveHTML($div);
} catch (Exception $e) {
echo 'Error ', $e->getMessage();
}
答案 0 :(得分:0)
curl_exec()
将在错误时返回false。在这种情况下你可以抛出异常:
function get_data($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
if($data === FALSE) {
$msg = curl_error($ch);
curl_close($ch);
throw new Exception($msg);
}
curl_close($ch);
return $data;
}