Search code examples
phptry-catchsymfony-3.3

try catch orm doctrine on symfony3.3 syntax


I am trying to Catch Doctrine exception in the controller by try catch, i am using Symfony 3

try {
   $em = $this->get('doctrine.orm.entity_manager');
   $em->persist( $transaction );
   $em->flush();
} catch(Exception $e) {
   return new JsonResponse(['error' => 'already exist']);
}

Thanks in advance


Solution

  • Finaly i got the solution for my problem and i wanna share the solution with you

    try {
       $em = $this->get('doctrine.orm.entity_manager');
       $em->persist( $transaction );
       $em->flush();
    } catch(\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
                throw new \Symfony\Component\HttpKernel\Exception\HttpException(409, "Transaction already exist" );
            } catch(\Doctrine\DBAL\Exception\ConstraintViolationException $e ) {
                throw new \Symfony\Component\HttpKernel\Exception\HttpException(409, "Bad request on Transaction" );
            } catch(\Doctrine\DBAL\Exception\TableNotFoundException $e ) {
                throw new \Symfony\Component\HttpKernel\Exception\HttpException(409, "Transaction Table not found" );
    }
    

    This link contains all Exception in Doctrine

    https://github.com/doctrine/dbal/tree/master/lib/Doctrine/DBAL/Exception