【问题标题】:Why isn't my PHP Error Handler Echoing All Errors?为什么我的 PHP 错误处理程序没有回显所有错误?
【发布时间】:2018-06-09 11:44:48
【问题描述】:

我有导致 2 个错误的代码,其中 1 个来自 php 函数 pg_query_params,因为我输入了一个无效查询,以及当该函数的结果为 false 时我抛出的异常:

if (!$res = pg_query_params($this->sql, $this->args)) {
        // note pg_last_error seems to often not return anything
        $msg = pg_last_error() . " " . $this->sql . PHP_EOL . " Args: " . var_export($this->args, true);
        throw new \Exception("Query Execution Failure: $msg");
    }

然后我有错误处理程序代码,它记录错误并应该回显它们。两个错误都被记录,但只有最后一个(抛出的异常)被回显。我希望两者都得到回应,因为第一个包含有用的调试信息。我不明白为什么两者都不是,因为我已经进行了一些调试,并且两个错误都调用了 echo 。它与输出缓冲或并发问题有关吗?

这是我的错误处理程序代码的缩短版本。 throwableHandler 方法用 set_exception_handler() 注册,phpErrorHandler 方法用 set_error_handler() 注册。我没有包含 generateMessageBodyCommon() 但它只是将错误信息添加到消息正文中:

private function handleError(string $messageBody, int $errno)
{
    // echo
    if ($this->echoErrors) {
        $messageBody .= 'inside echo'; // this goes into the log file for both errors
        echo nl2br($messageBody, false);
    }

    // log
    @error_log($messageBody, 3, $this->logPath);
}

public function throwableHandler(\Throwable $e)
{
    $message = $this->generateMessageBodyCommon($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
    $message .= PHP_EOL . "Stack Trace:" . PHP_EOL . $e->getTraceAsString();
    $this->handleError($message, $e->getCode(), $exitPage);
}

public function phpErrorHandler(int $errno, string $errstr, string $errfile = null, string $errline = null)
{
    $message = $this->generateMessageBodyCommon($errno, $errstr, $errfile, $errline) . PHP_EOL . "Stack Trace:". PHP_EOL . $this->getDebugBacktraceString();
    $this->handleError($message, $errno, false);
}

【问题讨论】:

    标签: php


    【解决方案1】:

    小心'@' -> @error_log($messageBody, 3, $this->logPath);

    PHP 支持一种错误控制运算符:at 符号 (@)。当附加到 PHP 中的表达式时,该表达式可能生成的任何错误消息都将被忽略。

    http://php.net/manual/en/language.operators.errorcontrol.php

    错误级别:

    error_reporting(E_ALL);
    

    http://www.php.net/manual/en/function.error-reporting.php

    error_reporting — 设置报告哪些 PHP 错误

    【讨论】:

    • 谢谢。我想如果我不使用它,并且错误日志有问题,就会出现无限循环。您认为这可能与回声问题有关吗?
    • error_reporting 或者ini_set('display_errors', true); ?
    • error_reporting(-1); // 所有,包括未来的类型 ini_set('display_errors', 'off'); ini_set('display_startup_errors', 'off');注意:我刚刚尝试将 ini_set 值设置为 on,但没有效果。
    • 我认为这个想法是将错误输出的控制权交给自定义错误处理程序。
    • 也许你的处理程序有问题,这会造成一个循环
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 2019-09-26
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多