php - 使用 file_get_contents 进行良好的错误处理

标签 php error-handling

我正在使用 simplehtmldom它有这个功能:

// get html dom form file
function file_get_html() {
    $dom = new simple_html_dom;
    $args = func_get_args();
    $dom->load(call_user_func_array('file_get_contents', $args), true);
    return $dom;
}

我是这样使用的:

$html3 = file_get_html(urlencode(trim("$link")));

有时,URL 可能无效,我想处理这个问题。我以为我可以使用 try and catch 但这没有用,因为它不会抛出异常,它只是给出这样的 php 警告:

[06-Aug-2010 19:59:42] PHP Warning:  file_get_contents(http://new.mysite.com/ghs 1/) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found  in /home/example/public_html/other/simple_html_dom.php on line 39

第 39 行在上面的代码中。

我怎样才能正确处理这个错误,我能不能只使用一个普通的 if 条件,它看起来不像返回 bool 值。

感谢大家的帮助

更新

这是一个好的解决方案吗?

if(fopen(urlencode(trim("$next_url")), 'r')){

    $html3 = file_get_html(urlencode(trim("$next_url")));

}else{
    //do other stuff, error_logging
    return false;

}

最佳答案

这是一个想法:

function fget_contents() {
    $args = func_get_args();
    // the @ can be removed if you lower error_reporting level
    $contents = @call_user_func_array('file_get_contents', $args);

    if ($contents === false) {
        throw new Exception('Failed to open ' . $file);
    } else {
        return $contents;
    }
}

基本上是 file_get_contents 的包装器。它会在失败时抛出异常。 为避免必须重写 file_get_contents 本身,您可以

// change this
$dom->load(call_user_func_array('file_get_contents', $args), true); 
// to
$dom->load(call_user_func_array('fget_contents', $args), true); 

现在您可以:

try {
    $html3 = file_get_html(trim("$link")); 
} catch (Exception $e) {
    // handle error here
}

错误抑制(通过使用 @ 或通过降低 error_reporting 级别是有效解决方案。这可能会抛出异常,您可以使用它来处理错误。那里file_get_contents 可能产生警告的原因有很多,PHP 手册本身建议降低 error_reporting: See manual

关于php - 使用 file_get_contents 进行良好的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3431169/

相关文章:

php - 在 CodeIgniter 中调用未定义的方法 CI_DB_mysqli_result::where()

mongodb - 有人可以帮助我解释重复键错误发生时的mongo插入过程吗?

php - 将大型本地数据库与服务器数据库 (MySQL) 同步

php - 有没有办法通过编写 PHP 来生成数据库?

php - 显示带有异常消息的变量值

r - #R#二进制运算符#xts对象的非数字参数*整数

error-handling - 带通配符的WorkflowError

exception - 为什么 Grails 会删除我的异常?

javascript - AJAX GET 未在页面加载时更新 Javascript 变量

javascript - 使用 JQuery 从 PHP 获取 JSON 响应