Maa*_*duk 3 php exception symfony symfony4
现在我正在尝试捕获这样的异常事件:
try {
echo 1 / 0;
} catch (\Exception $e){
$subs = new ExceptionSubscriber();
$this->dispatcher->addSubscriber($subs);
};
Run Code Online (Sandbox Code Playgroud)
我定义了 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';
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 services.yaml
App\EventSubscriber\ExceptionSubscriber:
tags:
- { name: kernel.event_subscriber, event: kernel.exception }
Run Code Online (Sandbox Code Playgroud)
我知道我捕获的常规 PHP 异常不是内核异常事件之一,在这种情况下我必须创建自定义异常事件,对吧?
我使用而不是侦听器调度事件的方式EventSubscriber很好
我是否必须分派这些事件,或者它们以某种神奇的方式传递给订阅者?
当抛出 an 时Exception(并且未处理它),HttpKernel捕获它并分派一个kernel.exception事件。
但在您的示例中,这永远不会发生,因为您自己捕获了异常。并试图在那里创建一个订阅者,这没有多大意义;如果有的话你会调度一个事件。但调度新事件是不必要的,因为该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
}
}
Run Code Online (Sandbox Code Playgroud)
您需要配置此类才能实际侦听这些事件:
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getException();
// inspect the exception
// do whatever else you want, logging, modify the response, etc, etc
}
}
Run Code Online (Sandbox Code Playgroud)
没有什么可做的。任何未捕获的异常都将通过这里。无需创建特定的try/catch块(尽管一般而言它们是一个好主意,因为处理您自己的异常通常是一件好事)。
这些地方的文档均对此进行了解释,其中包括: