尝试在symfony3.3语法上捕获orm学说

时间:2017-12-20 17:21:57

标签: php try-catch symfony-3.3

我试图通过try catch在控制器中捕获Doctrine异常,我正在使用Symfony 3

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

提前致谢

1 个答案:

答案 0 :(得分:1)

最终我得到了解决问题的方法,我想和你分享解决方案

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" );
}

此链接包含Doctrine中的所有异常

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