【问题标题】:PHP or MySql error; Possible to display an "error page" in browser?PHP 或 MySql 错误;可以在浏览器中显示“错误页面”吗?
【发布时间】:2011-02-20 10:38:52
【问题描述】:

我的分类网站主要使用 PHPMySql

出错时(例如,如果找不到变量),我想显示一个错误页面,这可能吗?我的意思是每个错误都指向同一个错误页面。

我正在考虑htaccess,但也许还有其他方法?

和MySql一样,那里是怎么做的?

谢谢

【问题讨论】:

  • 由于您有一个分类网站,我假设您的意思是,例如,www.mysite.com/cars.php?id=5,如果不存在 id=5 的汽车,您将被重定向到“找不到项目”类型的页面?你不是在谈论 PHP 的错误/警告/通知吧?
  • 如果你将用户重定向到一个通用的错误页面,你就不能再显示特定的错误消息了。显示通用错误页面不是一个好主意。

标签: php sql mysql html .htaccess


【解决方案1】:

您可以使用可能是您正在寻找的 PHP 错误处理方法来做一些事情。有一个不错的教程here

【讨论】:

    【解决方案2】:

    您可以附加自定义错误处理程序来执行重定向。首先开启输出缓冲,否则无法调用所需的header()函数。

    ob_start();
    
    // This function will be our custom error handler
    function redirect_on_error(int $errno , string $errstr) {
        // Ignore the error, just redirect the user to an error page
        ob_end_clean(); // Erase any output we might have had up to this point
        header('Location: error.html'); // Or wherever you want to redirect to
        exit;
    }
    
    set_error_handler('redirect_on_error'); // Set the error handler
    
    // Your code goes here
    
    ob_end_flush(); // End of the page, flush the output buffer
    

    【讨论】:

      【解决方案3】:

      就个人而言,我一直使用错误异常 (http://us.php.net/manual/en/class.errorexception.php)...

      所以,在我的代码开头,我有以下内容:

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

      然后,我将所有内容包装在一个巨大的 try{}catch{} 块中。所以我可以“捕捉”更高的错误,但如果我不这样做,它会向客户端显示一条错误消息:

      ob_start();
      try {
          //Do Stuff Here, include files, etc
      } catch (Exception $e) {
          ob_end_clean();
          //Log the error here, including backtraces so you can debug later
          //Either render the error page here, or redirect to a generic error page
      }
      

      美妙之处在于它可以捕捉到任何类型的错误。所以在我的 DB 类中,我只是抛出一个 DatabaseException(它扩展了 Exception)。因此,如果我想优雅地失败,我可以在拨打电话时尝试/捕捉它,或者我可以让它由顶部的 try{}catch 块处理。

      【讨论】:

        猜你喜欢
        • 2013-01-02
        • 2010-10-30
        • 2013-01-28
        • 1970-01-01
        • 2011-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多