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 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页