简体   繁体   中英

Handling cURL error inside a function?

I've seen the documentation, and several tutorials. However I can't get my code work handling errors. I just want to print "Error.", whatever error is.

Here's my code without handling error,

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();

EDIT: The next one prints the default error message, but not mine.

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();
}

curl_exec() will return false on errors. You can throw an Exception in this case:

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;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM