doushai7225 2014-10-11 14:52
浏览 61
已采纳

处理来自外部库的错误(simple_html_dom)

I'm building a page to crawl some web pages.

It works, usually, but everyone once in a while, it will fail to grab the page, and throw the following error:

( ! ) Warning: file_get_contents(URLWASHERE): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in Z:\Wamp\www\spider\simple_html_dom.php on line 555

Here is how I'm grabbing the page:

$page->load_file('URLWASHERE');

Is there a way to figure out if that error happens? I don't know how to detect it because it's in the library, not my code.

I can't use if (!$page) because it still returns something. But that something doesn't seem very helpful, though it is significantly shorter.


You can see output here:

$page when successful: http://pastebin.com/CnRVP6SK

$page when failed: http://pastebin.com/t9q6Gwnf


I just want to be able to find out if there was an error so I can have my program try again.

  • 写回答

2条回答 默认 最新

  • dqu92800 2014-10-11 15:27
    关注

    You can use the error_get_last() function to get info about the last error. You might also consider silencing the warning message with the @ operator.

    @file_get_contents('http://example.com/wjqlshqwd');
    
    $error = error_get_last();
    if($error && strpos($error['message'], '404') !== false)
    {
        echo 'There was an error';
    }
    

    Also before running this code you should reset the state of error_get_last(), a comment on the PHP manual page describes a trick to do that:

    // var_dump or anything else, as this will never be called because of the 0
    set_error_handler('var_dump', 0);
    @$undef_var;
    restore_error_handler();
    
    // error_get_last() is now in a well known state:
    // Undefined variable: undef_var
    

    The concept is just to create a known error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题