Doctrine Symfony2 – EntityManager Closed – Always enclose flush inside a try catch block and log exceptions

Hi,

This is not a tutorial but a good practice advice, about flush of objects in Doctrine with Symfony2.
A few days ago, we have encountered a strange error: “Entity Manager Closed”.

After several minutes of research, we found the problem.

We were trying to save a NULL value inside a NOT NULL field in our database, making the flush of objects failing.
When flush fails, it creates an exception like this:

 Doctrine\ORM\Exception "The EntityManager is closed".

When this error occurs, then entityManager is voluntarily closed, and following “flush” will not work.

The good practice is to systematically enclose all flush, inside a try catch block, and log the exception message and trace.
Let’s see an example.

    try {
        $em->flush();
    } catch (\Exception $e) {
        $msg = '### Message ### \n'.$e->getMessage().'\n### Trace ### \n'.$e->getTraceAsString();
        $this->container->get('logger')->critical($msg);
        // Here put you logic now you now that the flush has failed and all subsequent flush will fail as well
    }

This is a good practice that you’ll have to use in your further codes.

Doctrine Symfony2 – EntityManager Closed – Always enclose flush inside a try catch block and log exceptions