Catching database exceptions in Symfony2

前端 未结 2 1123
野趣味
野趣味 2021-01-07 11:45

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 e

相关标签:
2条回答
  • 2021-01-07 12:14

    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()
        }
    }
    
    0 讨论(0)
  • 2021-01-07 12:23

    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

    0 讨论(0)
提交回复
热议问题