1

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

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

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?

tux3
  • 7,171
  • 6
  • 39
  • 51
Steven Musumeche
  • 2,886
  • 5
  • 33
  • 55
  • That's the fact. Your error says too many connection, which must be configured on the mysql server side. – Emii Khaos Apr 20 '15 at 05:11
  • If you had read my question, you can see that I'm trying to setup a listener to debug the problem so that I can fix the server. It's already configured to accept 400 connections, so something is happening to cause it to lock up and that's why I asked this question. Your answer was really unhelpful. – Steven Musumeche Apr 20 '15 at 12:56

2 Answers2

8

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

In your services.yml you need to specify listener:

kernel.listener.your_pdo_listener:
        class: Acme\AppBundle\EventListener\YourExceptionListener
        tags:
           - { name: kernel.event_listener, event: kernel.exception, method: onPdoException }

Now you need to create this class:

YourExceptionListener:

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
class YourExceptionListener
{
     public function onPdoException(GetResponseForExceptionEvent $event)
     {
          $exception = $event->getException();

          if ($exception instanceof PDOException) {
              //now you can do whatever you want with this exception
          }
     }
}

Check doc how to create event listener

Tomasz Madeyski
  • 10,742
  • 3
  • 50
  • 62
2

Define a service like this:

<service id="app.listener.kernel.exception"
                 class="MyAppBundle\Listener\KernelExceptionListener">
            <tag name="kernel.event_listener" event="kernel.exception" method="onKernelException"/>
            <argument type="service" id="logger"/>
</service>

And a class like this:

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class KernelExceptionListener
{
    private $logger;

    public function __construct(Monolog\Logger $logger)
    {
        $this->logger = $logger;
    }

    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // Here check the exception
        //$event->getException()
    }
}
Aleksander Wons
  • 3,611
  • 18
  • 29