【问题标题】:How capture compilation errors from an include script?如何从包含脚本中捕获编译错误?
【发布时间】:2013-09-17 16:29:50
【问题描述】:

我想在函数中包含一个文件,并使用ob_start()ob_get_contents() 等将输出保存到一个文件中。

但如果包含的文件中有错误,我想要:

  1. 让我的函数知道并捕获它(以便它可以优雅地处理它)

  2. 不输出错误

set_error_handler 会允许这样做吗?

【问题讨论】:

    标签: php exception-handling ob-start ob-get-contents


    【解决方案1】:

    对于(大多数)非致命事件,是的,set_error_handler 可以捕捉到这些,您可以优雅地处理它们。

    对于致命错误,请查看此问题的答案:PHP : Custom error handler - handling parse & fatal errors

    现在,如果您有兴趣防止简单的解析错误,如果您能够为 PHP 安装安装扩展,则可以使用 runkit 扩展的runkit_lint_file。 [附录编辑:即在包含文件之前对文件进行 lint。解析错误不可恢复。这也可以通过使用 -l 选项在命令行上运行 php 来完成。尽管取决于您的主机的设置方式,您可能需要修改环境以使命令行 php 选项起作用。]

    这是一个使用命令行 php 的示例,但我不确定它是否是一个很好的示例。从我的一个项目中摘录并添加了一些 cmets。

    /**
     * Lint and and retrieve the result of a file. (If lint is possible)
     * @param $file
     * @return Mixed bool false on error, string on success.
     */
    function lint_and_include ($file) {
       if(is_readable($file)) {
          //Unset everything except PATH.
          //I do this to prevent CGI execution if we call
          //a CGI version of PHP.
          //Someone tell me if this is overkill please.
          foreach($_ENV as $key=>$value)
          {
             if($key == "PATH") { continue; }
             putenv($key);
          }
          $sfile = escapeshellarg($file);
          $output = $ret = NULL;
          //You could modify this to call mandatory includes to 
          //also catch stuff like redefined functions and the like.
          //As it is here, it'll only catch syntax errors.
          //You might also want to point it to the CLI php executable.
          exec("php -l $sfile", $output, $return);
          if($return == 0) {
             //Lint Okay
             ob_start();
             include $file;
             return ob_get_clean();
          }
          else {
             return false;
          }
       }
       else {
          return false;
       }
    }
    

    附加说明:在这种情况下,您的set_error_handler 回调应该记录它可以在某处捕获的错误,而不是输出它们。如果包含的任何代码都可能引发异常,您可能还需要使用 try-catch 块来捕获这些异常。

    【讨论】:

    • 糟糕,我注意到我没有正确阅读标题,您可能只对第三段感兴趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2018-01-18
    • 2012-01-25
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多