'How to reopen Doctrine Entity Manager after DBALException
I have a console application with Symfony 2, the script run on cron (terminal). But, after \Doctrine\DBAL\DBALException the script throw N \Doctrine\ORM\ORMException with message "The EntityManager is closed.".
This is partial of script:
try {
$this->getDoctrine()->getConnection()->beginTransaction();
// ...
$manager = $this->getDoctrine()->getManager();
$entity = new Post();
$entity
->setAuthor($author)
->setTitle($title)
->setContent($content)
;
$manager->persist($entity);
$manager->flush();
$this->getDoctrine()->getConnection()->commit();
return $entity->getId();
} catch (\Doctrine\DBAL\DBALException $e) {
$this->getDoctrine()->resetManager();
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
} catch (\Exception $e) {
$this->getDoctrine()->getConnection()->rollback();
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
}
How to fix it?
Solution 1:[1]
You can reset your entity manager manualy like this :
//...
} catch (\Doctrine\DBAL\DBALException $e) {
$manager = $this->getDoctrine()->getManager();
if (!$manager->isOpen()) {
$manager = $manager->create(
$manager->getConnection(),
$manager->getConfiguration()
);
}
$output->writeln(sprintf(
'<error>[!] %s (%s) the post could not be created "%s"</error>',
get_class($e),
date('Y-m-d H:i:s'),
$e->getMessage()
));
return false;
}
//...
Solution 2:[2]
On Symfony 5 I reopened connection in this way:
} catch (\Doctrine\DBAL\Driver\Exception $e) {
/** @var \Doctrine\Persistence\ManagerRegistry $managerRegistry */
$managerRegistry->resetManager();
}
I have seen other cases where they use return value of resetManager(): ObjectManager as new entity manager instead of continuing using the same entity manager. But it is unnecessary, you can continue using the same entity manager.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | j-guyon |
| Solution 2 | Nuryagdy Mustapayev |
