Search code examples
phptry-catchfile-get-contents

php try catch not working properly


I have code like this:

try {   
    $providerError = false;
    $providerErrorMessage = null;
    $nbg_xml_url = "http://www.somesite.com/rss.php";
    $xml_content = file_get_contents($nbg_xml_url);
    // ... some code stuff
} catch (Exception $e) {
    $providerError = true;
    $providerErrorMessage = $e -> getMessage();
    $usd = 1;
    $rate = null;
    $gel = null;
} finally {
    // .. Write in db 
}`

and problem is that, when file_get_contents can not read url (may be site not responding or something like this..) my code writes error: failed to open stream: HTTP request failed! and execution goes direct to finally block bypass catch block without entering in it..

any ideas?


Solution

  • You can set an empty error handler to prevent the warning and afterward throw a custom exception in case of failure. In this case I would write a custom file_get_content like so:

    function get_file_contents($url) {
    
        $xml_content = file_get_contents($url);
    
        if(!$xml_content) {
            throw new Exception('file_get_contents failed');
        }
    
        return $xml_content;
    } 
    

    and would use it in your block:

    set_error_handler(function() { /* ignore errors */ });
    
    try {   
        $providerError = false;
        $providerErrorMessage = null;
        $nbg_xml_url = "http://www.somesite.com/rss.php";
    
        $xml_content = get_file_contents($nbg_xml_url); //<----------
    
        // ... some code stuff
    } catch (Exception $e) {
        $providerError = true;
        $providerErrorMessage = $e -> getMessage();
        $usd = 1;
        $rate = null;
        $gel = null;
    } finally {
        // .. Write in db 
    }
    

    Then remember to restore the error handler calling:

    restore_error_handler();
    

    Note that when using your own error handler it will bypass the

    error_reporting

    setting and all errors included notices, warnings, etc., will be passed to it.