我有一个随机问题,我无法缩小范围。偶尔,我会在Symfony2应用程序中收到以下错误:
未捕获的异常:驱动程序中发生异常:SQLSTATE[08004] [1040] 连接过多 {"type":1,"file":"/var/www/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line":115,"level":30709
我想设置一个应用程序范围的侦听器来捕获PDOException
并记录一些信息。我怎样才能连接到Symfony只捕捉PDOException
?
您需要创建自定义异常侦听器。它将侦听所有异常,但您将在其中指定类型检查。
在services.yml
中,您需要指定侦听器:
kernel.listener.your_pdo_listener:
class: AcmeAppBundleEventListenerYourExceptionListener
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onPdoException }
现在你需要创建这个类:
您的异常侦听器:
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
class YourExceptionListener
{
public function onPdoException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof PDOException) {
//now you can do whatever you want with this exception
}
}
}
查看文档如何创建事件侦听器
定义如下服务:
<service id="app.listener.kernel.exception"
class="MyAppBundleListenerKernelExceptionListener">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException"/>
<argument type="service" id="logger"/>
</service>
还有这样的类:
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
class KernelExceptionListener
{
private $logger;
public function __construct(MonologLogger $logger)
{
$this->logger = $logger;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
// Here check the exception
//$event->getException()
}
}