php try catch无法正常工作

时间:2015-12-04 18:13:52

标签: php try-catch file-get-contents

我有这样的代码:

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

问题是,当file_get_contents无法读取url(可能是网站没有响应或类似的东西..)时,我的代码写错误:failed to open stream: HTTP request failed!并执行直接到最后阻止绕过catch阻止而不进入..

任何想法?

2 个答案:

答案 0 :(得分:2)

您可以设置空错误处理程序以防止警告,然后在发生故障时抛出自定义异常。在这种情况下,我会像这样写一个自定义file_get_content

function get_file_contents($url) {

    $xml_content = file_get_contents($url);

    if(!$xml_content) {
        throw new Exception('file_get_contents failed');
    }

    return $xml_content;
} 

并将在您的块中使用它:

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 
}

然后记得恢复错误处理程序调用:

restore_error_handler();

请注意,使用自己的错误处理程序时,它将绕过

  

的error_reporting

设置和包含通知,警告等的所有错误都将传递给它。

答案 1 :(得分:0)

$xml_content = file_get_contents($nbg_xml_url);

函数file_get_contents不会抛出异常。因此,如果没有找到该文件,则不会抛出异常。

来自文档:

  

如果找不到文件名,则会生成E_WARNING级别错误...

此函数返回读取数据或失败时返回FALSE。因此,您可以检查$ xml_content是否为FALSE($ xml_content === false)并相应地继续。

相关问题