在 Symfony2 中捕获数据库异常

2022-01-03 00:00:00 php symfony doctrine pdo doctrine-orm

我遇到了一个无法缩小范围的随机问题.有时,我会在 Symfony2 应用程序中收到以下错误:

I've got a random problem that I can't narrow down. Occasionally, I will get the following error in a Symfony2 application:

未捕获的异常:驱动程序中发生异常:SQLSTATE[08004] [1040] 连接太多 {"type":1,"file":"/var/www/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line":115,"level":30709

Uncaught Exception: An exception occured in driver: SQLSTATE[08004] [1040] Too many connections {"type":1,"file":"/var/www/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line":115,"level":30709

我想设置一个应用程序范围的侦听器来捕获 PDOException 并记录一些信息.我怎样才能挂钩到 Symfony 只捕获 PDOException?

I would like to setup an application-wide listener to catch the PDOException and log some information. How can I hook into Symfony to only catch PDOException?

推荐答案

您需要创建自定义异常侦听器.它将侦听所有异常,但您将在其中指定类型检查.

You need to create custom exception listener. It will listen to all exceptions, but you will specify type check inside it.

在您的 services.yml 中,您需要指定侦听器:

In your services.yml you need to specify listener:

kernel.listener.your_pdo_listener:
        class: AcmeAppBundleEventListenerYourExceptionListener
        tags:
           - { name: kernel.event_listener, event: kernel.exception, method: onPdoException }

现在你需要创建这个类:

Now you need to create this class:

你的异常监听器:

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
          }
     }
}

检查文档 如何创建事件监听器

相关文章