gpt4 book ai didi

symfony - 如何降低 NotFoundHttpException 的严重性?

转载 作者:行者123 更新时间:2023-12-02 09:02:42 24 4
gpt4 key购买 nike

当我的 Symfony2 应用程序中发生不良情况时,我希望收到警报。现在我只是在日志中查找ERROR。不幸的是,“HTTP 404 - 文件未找到”(NotFoundHttpException) 被记录为错误,“HTTP 403 - 禁止”(AccessDeniedHttpException) 也是如此。

这并不保证错误;这些最多应该是警告。我怎样才能使这些日志处于不太严重的级别?

错误示例:

[2012-07-02 16:58:21] request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route found for "GET /foo" (uncaught exception) at /home/user/Symfony2_v2.0.12/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/EventListener/RouterListener.php line 83 [] []

最佳答案

我发现了一些有用的东西。 Symfony2 internals doc on the kernel.exeption event提到可以对事件设置响应,并且 GetResponseForExceptionEvent docs

The propagation of this event is stopped as soon as a response is set.

我拼凑了一个监听器,它似乎可以做我想要的事情:

<?php

namespace Acme\DemoBundle\Listener;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class ExceptionLoggingListener {
private $logger;

public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}

public function onKernelException(GetResponseForExceptionEvent $event) {
if(!$event) {
$this->logger->err("Unknown kernel.exception in ".__CLASS__);
return;
}
$notFoundException = '\Symfony\Component\HttpKernel\Exception\NotFoundHttpException';

$e = $event->getException();
$type = get_class($e);
if ($e instanceof $notFoundException) {
$this->logger->info($e->getMessage());
$response = new Response(Response::$statusTexts[404], 404);
$event->setResponse($response);
return;
}

$accessDeniedException = '\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException';
if ($e instanceof $accessDeniedException) {
$this->logger->info($e->getMessage());
$response = new Response(Response::$statusTexts[403], 403);
$event->setResponse($response);
return;
}
$this->logger->err("kernel.exception of type $type. Message: '".$e->getMessage()."'\nFile: ".$e->getFile().", line ".$e->getLine()."\nTrace: ".$e->getTraceAsString());
}

}

关于symfony - 如何降低 NotFoundHttpException 的严重性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com