现在我正在尝试捕获这样的异常事件:
try {
echo 1 / 0;
} catch (\Exception $e){
$subs = new ExceptionSubscriber();
$this->dispatcher->addSubscriber($subs);
};
我定义了 ExceptionSubscriber ,如下所示:
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => [
['processException', 10],
['exception', -10],
],
];
}
public function exception(ExceptionEvent $event)
{
echo 'test321';
}
public function processException(ExceptionEvent $event)
{
echo 'test123';
}
}
这是我的 services.yaml
App\EventSubscriber\ExceptionSubscriber:
tags:
- { name: kernel.event_subscriber, event: kernel.exception }
我知道我捕获的常规 PHP 异常不是内核异常事件之一,在这种情况下我必须创建自定义异常事件,对吧?
我使用调度事件的方式EventSubscriber
,不听者就好
我是否必须分派这些事件,或者它们以某种神奇的方式传递给订阅者?
When an Exception
被抛出(并且没有被处理),HttpKernel
捕获它并发送一个kernel.exception
event.
但在您的示例中,这永远不会发生,因为您自己捕获了异常。并试图在那里创建一个订阅者,这没有多大意义;如果有的话你会调度一个事件。但调度新事件是不必要的,因为kernel.exception
事件已由框架调度。
如果您想捕获该事件,您需要创建自己的事件侦听器。一个基本的例子:
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getException();
// inspect the exception
// do whatever else you want, logging, modify the response, etc, etc
}
}
您需要配置此类才能实际侦听这些事件:
services:
App\EventListener\ExceptionListener:
tags:
- { name: kernel.event_listener, event: kernel.exception }
没有什么可做的。任何未捕获的异常都将通过这里。无需创建特定的try/catch
块(尽管一般而言它们是一个好主意,因为处理您自己的异常通常是一件好事)。
这些地方的文档均对此进行了解释,其中包括:
- 使用 kernel.exception 事件 https://symfony.com/doc/current/controller/error_pages.html#working-with-the-kernel-exception-event
- 创建事件监听器 https://symfony.com/doc/current/event_dispatcher.html#creating-an-event-listener
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)