Yassine Ah
Yassine Ah

Reputation: 1

symfony2 can't catch PDOException

I want to catch PDOException in symfony 2.6, especially ConnectionException.

For instance if I stop my MySQL server I want to catch that exception and return a customised message to the user, but it seem that it's uncatchable in customised kernel.exception listner, and either in try catch block, i don't know if it's a symfony problem or something must be done.

I also tried out to customise error page like said in documentation but usselssly, I seached in web for solution, but I found nothing except something about redefining a controller in frameworkbundle whish is responsable of converting Exception into error page.

But I really don't want to go for that solution since i'm new with symfony.

Upvotes: 0

Views: 955

Answers (1)

Nawfal Serrar
Nawfal Serrar

Reputation: 2263

You can do this by creating an exception listener and catch Pdo exception :

service.yml:

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

Then the listener class :

YourExceptionListener

UPDATED

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

          if ($exception instanceof \PDOException || $exception->getPrevious() instanceof \PDOException) {
              //now you can do whatever you want with this exception
          }
     }
}

Snippets from : Catching database exceptions in Symfony2

I have done more test, so the test i made first was making a query to the database, that's why i got pdoexception as first exception but sometime it can be a twig exception as you know twig throw runtime exception if it couldn't contact database but hopefully we can get the previous exception also and this can work with other exceptions which can be thrown after the PDO ones, so hopefully it will work for you as expected so i edited the code to check if previous exception is a PDOException also.

Upvotes: 1

Related Questions