0

考虑这个简单的子类PrettyPageHandler

class NewErrorHandler extends \Whoops\Handler\PrettyPageHandler
{
    public $foo = null;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->foo = 'bar';

        echo 'executed';
    }
}

当这样使用时:

$errorHandler = new NewErrorHandler();
$whoops->pushHandler($errorHandler);
$whoops->register();
var_dump($errorHandler->foo);

$errorHandler->foo为空,但打印了“已执行”。$this->foo = 'bar';即使它应该已经在此过程中执行或无效,它似乎也没有执行或无效。任何想法为什么?

更新 1

我正在尝试handle();通过工作正常的输出缓冲获得输出。但同时我想设置一个var:

    public function handle()
    {           
        parent::handle();
        $output = ob_get_clean();

        echo 'executed';

        $this->foo = 'bar';
    }

$this->foo = 'bar';此时似乎没有执行,但会打印“已执行”。

更新 2

我正在尝试确定错误是否尚未记录,如果为真,请执行发送通知(例如,电子邮件/短信/等)之类的操作。如果错误已被记录,则表示它是重复的,不再发送通知。这里有更多代码,但为了清楚起见进行了简化:

<?php

class NewErrorHandler extends \Whoops\Handler\PrettyPageHandler
{
    private $errorHash;
    private $isNewError;    

    public function __construct()
    {
        parent::__construct();
    }    

    public function handle()
    {
        parent::handle();
        $output = ob_get_clean();

        $this->setErrorHash();

        if (!$this->isDuplicateError()) {

            $this->isNewError = true;

            $this->log($output);    
        }
    }

    private function log(string $data): void
    {
        $filename = $this->errorHash . '.html';   

        file_put_contents('logs/errors/'. $filename, $data);
    }

    public function isDuplicateError(): bool
    {
        // code check if the file $this->errorHash.'.html' exists in logs/errors/
        // ...
    }

    private function setErrorHash(): string
    {
        $ex = $this->getException();

        $this->errorHash = md5($ex->getMessage() . $ex->getFile() . $ex->getLine() . $ex->getTraceAsString());
    }
}

$errorHandler = new NewErrorHandler();
$whoops->pushHandler($errorHandler);
$whoops->register();
if ($errorHandler->isNewError == true)
{
     // do something like send notifications... outside the child class.
}

问题是$errorHandler->isNewError空的,即使它应该是true

更新 3:

我将尝试解释我对为什么这应该起作用的想法。这是我正在尝试做的一个基本示例。让我们假设有一个简化的Whoops类叫做FakeWhoops

<?php

class FakeWhoops
{
    private $handler;

    public function pushHandler(CustomHandler $handler)
    {
        $this->handler = $handler;
    }

     public function triggerError()
    {
        $this->handler->handle();
    }
}

这是我的自定义处理程序:

class CustomHandler
{
    public $foo;

    public function handle()
    {       
        $this->foo = true;
        echo 'executed';
    }
}

现在让我们运行它并触发一个假错误:

$cH = new CustomHandler;

$fW = new FakeWhoops;
$fW->pushHandler($cH);

// let's trigger a fake error which should call CustomHandler::handle();
$fW->triggerError();

var_dump($cH->foo); // returns true, foo was set!

正如你在这里看到的,这正是我想要做的,尽管使用的是真实的Whoops. 这是同样简单的想法。但是为什么这适用于这个简化的例子而不适用于Whoops

4

0 回答 0