【问题标题】:Ignoring PHP error, while still printing a custom error message忽略 PHP 错误,同时仍打印自定义错误消息
【发布时间】:2009-05-19 16:47:48
【问题描述】:

所以:

@fopen($file);

忽略任何错误并继续

fopen($file) or die("Unable to retrieve file");

忽略错误,终止程序并打印自定义消息

是否有一种简单的方法可以忽略函数中的错误、打印自定义错误消息而不终止程序?

【问题讨论】:

  • 如果您正确配置display_errors,您可以在保持与显示错误的兼容性的同时保留@运算符(您应该只在开发时这样做 - 如果有的话)。

标签: php error-handling


【解决方案1】:

通常:

if (!($fp = @fopen($file))) echo "Unable to retrieve file";

或使用您的方式(丢弃文件句柄):

@fopen($file) or printf("Unable to retrieve file");

【讨论】:

    【解决方案2】:

    使用例外:

    try {
       fopen($file);
    } catch(Exception $e) {
       /* whatever you want to do in case of an error */
    }
    

    更多信息http://php.net/manual/language.exceptions.php

    【讨论】:

    【解决方案3】:

    slosd 的方式行不通。 fopen 不会引发异常。你应该手动把它扔掉 我将修改您的第二个示例并将其与 slosd 的结合起来:

    try
    {
        if (!$f = fopen(...)) throw new Exception('Error opening file!');
    } 
    catch (Exception $e)
    {
        echo $e->getMessage() . ' ' . $e->getFile() . ' at line ' . $e->getLine;
    }
    echo ' ... and the code continues ...';
    

    【讨论】:

      【解决方案4】:

      这是我自己的解决方案。请注意,它需要脚本级别的全局变量或类的静态变量,以便于参考。我把它写成类样式供参考,但只要它可以找到数组就可以了。

      class Controller {
        static $errors = array();
      }
      
      $handle = fopen($file) or array_push(Controller::errors,
        "File \"{$file}\" could not be opened.");
      
       // ...print the errors in your view
      

      【讨论】:

        【解决方案5】:

        您可以抛出异常并以您认为合适的任何方式集中处理错误:-)

        【讨论】:

          猜你喜欢
          • 2016-12-03
          • 1970-01-01
          • 1970-01-01
          • 2018-08-08
          • 1970-01-01
          • 1970-01-01
          • 2017-09-26
          • 1970-01-01
          • 2023-02-22
          相关资源
          最近更新 更多