CakePHP 4排除选定的MissingControllerException

m528fe3b  于 2023-11-19  发布在  PHP
关注(0)|答案(1)|浏览(202)

在CakePHP 4中,我如何才能完全排除一个选定的MissingControllerException,它发生在名为MyImg的Controller类中?我想报告所有其他MissingControllerException错误(除了名为MyImg的Controller类)

hc8w905p

hc8w905p1#

您可以通过使用自定义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);
    }
}

相关问题