How to reopen Doctrine Entity Manager after DBALException

I have a console application with Symfony 2, the script runs on cron (terminal). But after \ Doctrine \ DBAL \ DBALException, the script will throw N \ Doctrine \ ORM \ ORMException with the message "EntityManager closed."

This is part of the 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?

+4
source share
1 answer

You can reset manage your entity manager as follows:

//...
} 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;
} 
//...
+6
source

All Articles