代码之家  ›  专栏  ›  技术社区  ›  Maksim Vi.

PHP文档错误处理

  •  20
  • Maksim Vi.  · 技术社区  · 16 年前

    但有时此url可能无效。在这种情况下,我需要处理错误。

    $xdoc = new DOMDocument();
    try{
      $xdoc->load($url); // This line causes Warning: DOMDocument::load(...)
                         // [domdocument.load]: failed to open stream: 
                         // HTTP request failed! HTTP/1.1 404 Not Found in ...
    } catch (Exception $e) {
      $xdoc = null;
    }
    
    if($xdoc == null){
      // Handle
    } else {
      // Proceed
    }
    

    我知道我可能做错了,但处理此类异常的正确方法是什么?我不想在我的页面上看到错误消息。

    DOMDocument::load()的手册上说:

    如果将空字符串作为 将生成警告。这 无法使用libxml的错误处理 处理功能。

    谢谢

    5 回复  |  直到 16 年前
        1
  •  39
  •   Øystein Riiser Gundersen    16 年前

    从我所能收集到的 documentation libxml_get_last_error() . 您可以使用错误抑制运算符并检查 false ...

    if (@$xdoc->load($url) === false)
        // ...handle it
    

    …或注册 an error handler which throws an exception on error :

    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }
    

        2
  •  8
  •   Markus Hedlund    15 年前
    set_error_handler(function($number, $error){
        if (preg_match('/^DOMDocument::loadXML\(\): (.+)$/', $error, $m) === 1) {
            throw new Exception($m[1]);
        }
    });
    
    $xml = new DOMDocument();
    $xml->loadXML($xmlData);
    
    restore_error_handler();
    

    这在PHP5.3中适用。但是如果你不使用 loadXML ,您可能需要进行一些修改。

        3
  •  5
  •   Petah    15 年前

    要禁用抛出错误,请执行以下操作:

    $internal_errors = libxml_use_internal_errors(true);
    
    $dom = new DOMDocument();
    // etc...
    
    libxml_use_internal_errors($internal_errors);
    
        4
  •  1
  •   Galen    16 年前

    来自php.net

    警告不是由libxml和 无法使用libxml的错误处理 处理功能。

    在生产环境中,不应该向用户显示错误。他们不需要看到他们,所以考虑到这一点,你可以使用。。。

    $xdoc = new DOMDocument();
    if ( $xdoc->load($url) ) {
        // valid
    }
    else {
        // invalid
    }
    
        5
  •  0
  •   sumit    12 年前

    $feed = new DOMDocument();  
    $res= @$feed->load('http://www.astrology.com/horoscopes/daily-extended.rss');
    if($res==1){
               //do sth
              }