【问题标题】:PHP get warning and error messages?PHP得到警告和错误信息?
【发布时间】:2013-02-23 03:46:36
【问题描述】:

我想在 php $variables 中获取警告和错误消息,所以我将它们保存到我的数据库中。

例如当出现任何类型的错误、警告或类似情况时:

Parse error: syntax error, unexpected T_VARIABLE in /example.php(136) on line 9
Warning: [...]

我想让它们进入变量 $error_code

这是怎么做到的?

【问题讨论】:

标签: php error-handling


【解决方案1】:

对于仅记录它们的简单情况:

set_error_handler(function($errno, $errstr, $errfile, $errline) use ($db) {
    // log in database using $db->query()
});

您还可以让这些警告、通知等生成异常:

function exception_error_handler($errno, $errstr, $errfile, $errline)
{
    if (error_reporting()) { // skip errors that were muffled
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
}

set_error_handler("exception_error_handler");

来源:ErrorException

异常会产生更严重的副作用,所以你应该有一个exception handler,以防止未捕获的异常导致白页死机。

【讨论】:

    【解决方案2】:

    查看set_error_handler()

    设置用户函数 (error_handler) 以处理脚本中的错误。

    此函数可用于定义您自己的错误处理方式 在运行时,例如在您需要执行的应用程序中 发生严重错误或需要时清理数据/文件 在特定条件下触发错误(使用 trigger_error())。

    【讨论】:

      【解决方案3】:

      我正在使用error_get_last();,直到找到更好的解决方案

      $lastError = error_get_last();
      echo $lastError ? "Error: ".$lastError["message"]." on line ".$lastError["line"] : "";
      // Save to db
      

      【讨论】:

        【解决方案4】:

        有一个名为 $php_errormsg 的变量用于获取先前的错误消息。在这里查看更多信息 - http://php.net/manual/en/reserved.variables.phperrormsg.php

        【讨论】:

          猜你喜欢
          • 2015-07-28
          • 2018-05-06
          • 1970-01-01
          • 2015-12-30
          • 1970-01-01
          • 2012-05-18
          • 1970-01-01
          • 2018-09-27
          • 2010-11-19
          相关资源
          最近更新 更多