2

I am trying to catch exceptions inside an Action in a Controller in Symfony2.3 application during entity persistance.

 try {
            $em->persist($firm);
     } catch(\Exception $e){
             .........
     }

I expected that all errors will be handled by my code inside catch statement, instead I got following errors:

[2/2] DBALException: An exception occurred while executing 'INSERT INTO ...
...
[1/2] PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry
...
CRITICAL - Uncaught PHP Exception Doctrine\DBAL\DBALException

If I throw exception inside try statement it is cought and handled properly by code inside catch

try {
           throw new \Doctrine\ORM\ORMException;
           //or throw new \Doctrine\DBAL\DBALException;
           //or throw new \PDOException;
    } catch(\Exception $e){
      .......        
    }

My question is: How one should properly handle Doctrine2 inside Symfony2 controller. Thanks.

2 Answers 2

3

Possible that you have got exception from line $em->flush() which doesnt wrapped with try-catch statement.

Sign up to request clarification or add additional context in comments.

2 Comments

that's the first thing that came to my mind. persist() does not actually executes any sql. It has to come from flush(). So you should wrap the flush() call in your try statement too.
Yes. That was the reason. My bad! Thank you forgottenbas, Florian, nifr.
3
Integrity constraint violation: 1062 Duplicate entry

In your case you should check for uniqueness before persisting your entity using the UniqueEntity validator.

If the form does not validate - just don't persist in order to avoid this exception.

1 Comment

Thanks! That is a helpful hint. I will go in that direction if I cannot figure it out with try-catch block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.