PHP的尝试赶上不能正常工作

Arkadi

我有这样的代码:

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块而没有进入的过程。

有任何想法吗?

甲酚

您可以设置一个空的错误处理程序以防止警告,并在失败后抛出自定义异常。在这种情况下,我将这样编写一个自定义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();

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

错误报告

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章