Symfony2-在$ em-> remove()上捕获异常

Ign*_*kis 1 doctrine exception entitymanager symfony doctrine-orm

我试图在执行时捕获异常:

try {
    $em->remove($education);
    $em->flush();
} catch(PDOException $e) {
    var_dump($e->getMessage());
    die;
}
Run Code Online (Sandbox Code Playgroud)

我也尝试了\Exception\Doctrine\ORM\ORMException,但没有一个起作用。

我得到的是相同的错误,而不是转储异常消息,我试图避免捕获异常:

[3/3] ForeignKeyConstraintViolationException:执行“从Trainee_education WHERE id =?中删除”时发生异常。带有参数[2]:

SQLSTATE [23000]:违反完整性约束:1451无法删除或更新父行:外键约束失败(trainingexperienceinternship,CONSTRAINT FK_10D1B00C2CA1BD71 FOREIGN KEY(education_id)参考trainee_educationid))

我知道为什么我的约束失败了,没有新内容。但是我想得到一个例外,这样我可以通知用户他无法删除对象,因为他在创建关系之前曾使用过该对象。

小智 5

我有同样的情况,但是我使用\ Doctrine \ DBAL \ DBALException

try{

      $em->persist($question);
      $em->flush();
} catch (\Doctrine\DBAL\DBALException $e) {

      $exception_message = $e->getPrevious()->getCode();
    return $this->render('AppBundle:Errors:error.html.twig', array('error' => $exception_message)); 

} 
Run Code Online (Sandbox Code Playgroud)

我不知道这是否是最佳解决方案,但可以。