CakePHP 4 排除选定的 MissingControllerException

CakePHP 4 excluding selected MissingControllerException

提问人:Annabelle 提问时间:10/3/2023 更新时间:10/24/2023 访问量:28

问:

在 CakePHP 4 中,我怎样才能从记录中完全排除名为 MyImg 的 Controller 类发生的选定 MissingControllerException?我想报告所有其他 MissingControllerException 错误(除了名为 MyImg 的 Controller 类的错误)

蛋糕PHP

评论

0赞 Salines 10/4/2023
创建自己的 MissingControllerException 并排除该控制器 阅读更多: book.cakephp.org/4/en/development/...
0赞 Annabelle 10/4/2023
我尝试按照您的建议编写自己的函数 missingController,页面已呈现,但日志仍添加到 error.log 中。我的目的不是在 error.log 中报告此类日志

答:

0赞 wowDAS 10/24/2023 #1

可以使用自定义 ErrorLogger 来实现此目的。

'Error' => [
    'logger' => \App\Error\ErrorLogger::class,
    'log' => true,
    ...
],

现在在 src/Error 文件夹中创建类 ErrorLogger:

<?php

declare(strict_types=1);

namespace App\Error;

use Cake\Controller\Exception\MissingControllerException;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;

class ErrorLogger extends \Cake\Error\ErrorLogger
{
    public function logException(Throwable $exception, ?ServerRequestInterface $request = null, bool $includeTrace = false): void
    {
        if ($request !== null) {
            if ($exception instanceof MissingControllerException) {
                $requestTarget = $request->getRequestTarget();

                $checkUrlStarts = [
                    '/myimg',
                ];

                foreach ($checkUrlStarts as $urlStart) {
                    if (str_starts_with($requestTarget, $urlStart)) {
                        // skip logging
                        return;
                    }
                }
            }
        }

        parent::logException($exception, $request, $includeTrace);
    }
}