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?
The EntityManager becomes closed as soon as an SQL exception is thrown by the underlying connection. The "real" exception has surely occurred before that. You will need a new EntityManager.
The last state, Detached, represents entity objects that have been disconnected from the EntityManager. For instance, all the managed objects of an EntityManager become detached when the EntityManager is closed.
The EntityManager is the central access point to ORM functionality. It can be used to find, persist, flush and remove entities.
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;
}
//...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With