friday-json
friday-json

Reputation: 137

Symfony Doctrine catch connection exception

I am working on a Symfony 5 project and I need to instantiate a new (dynamic) class and pass to it a db connection, if exists:

    $var = "name-of-my-connection";
    $this->container->get('doctrine')->getManager($var);

Not all these classes need a connection, in this case there's no db connection in doctrine.yaml for this specific class. I need to trap this error: Doctrine ORM Manager named "name-of-my-connection" does not exist.

Thanks.

Upvotes: 1

Views: 1119

Answers (1)

Alexandre Tranchant
Alexandre Tranchant

Reputation: 4551

To trap this error, you could catch the thrown exception. In this case, you should catch the InvalidArgumentException.

try{
   $nonExistentManager = $this->getDoctrine()->getManager('foo');
} catch (\InvalidArgumentException $e) {
   //The foo manager does not exist, do something
   //Redirect ?
}

If you are searching the list of available managers, you can use the getManagers method. This will return an array list of managers. The keys of this array are the available names:

$managers = $this->getDoctrine()->getManagers();
dd($managers);

this code returns something like this:

array:1 [▼
  "default" => Doctrine\ORM\EntityManager {#320 …11},
  "foo" => Doctrine\ORM\EntityManager {#321 …12},
  "bar" => Doctrine\ORM\EntityManager {#322 …12}
]

Upvotes: 1

Related Questions