【问题标题】:Catch all PHP errors and put in a var [closed]捕获所有 PHP 错误并放入 var [关闭]
【发布时间】:2013-11-07 05:59:18
【问题描述】:

我有多个 php 应用程序,当出现一些 php 错误时,它会记录到 Apache 日志文件中。

我需要有一个检测器来检测脚本中何时发生 php 错误。因此,当它检测到一个新的 php 错误时,可以将错误消息放入 var 或保存在数据库中。

【问题讨论】:

标签: php


【解决方案1】:

这基本上归结为两种错误。语法/解析器错误,以及运行时/逻辑错误。

对于语法/解析器错误,您可能不走运。在这些情况下,脚本本身无法执行,因此根据定义,脚本无法响应错误。对此最好的防御是测试(最好是自动化的)。您可以做的一件事是set your error logging to be a database instead of a file。但是脚本本身仍然无法响应错误。

对于运行时/逻辑错误,这就是exception handling 发挥作用的地方。有很多内容可以介绍,但整体结构很简单:

try {
    // perform some operation
} catch (Exception $e) {
    // an error occurred, the details of which are in $e
    // meaningfully respond to it
}

【讨论】:

  • 根据我的经验,异常实际上会干扰日志记录。记录它们需要要么在一个地方捕获所有错误(即使是最小的错误也是致命的),或者在任何地方重复“记录这个异常”。
【解决方案2】:

您可以使用 PHP 的输出缓冲区将某个代码块中的所有输出存储到一个变量中。这是一个例子:

ob_start();
// php code goes here
try{
   // Some code
}catch(Exception $e){
    echo $e->getMessage();
}
$all_output = ob_get_clean();

// Insert the $all_output string into database or log it into a file

在这种情况下,所有输出(例如警告)和在 ob_start 和 ob_get_clean 之间回显的任何其他内容都将存储在 $all_output 变量中。希望有帮助:)

【讨论】:

  • 谢谢。有没有另一种方法来编写这段代码?类似 set_exception_handler('yourExceptionHandler');函数 yourExceptionHandler($exception) {...} ?
  • @ihtus RTFM
  • set_exception_handler 只告诉 PHP 如何处理 uncaught 异常。如果处理程序确实运行,PHP 将要死掉。如果可以从错误中恢复并且您只想收到其发生的通知,这将不适合。
【解决方案3】:

您可以捕获关闭错误并将其插入数据库:

register_shutdown_function('shutdownFunction');

function shutDownFunction() { 
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do whatever
    } 
}

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 2011-07-16
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多