Tuesday, June 28, 2016

How to catch Exception in symfony 2 ?

You should take care for the exceptions that could be raised:
try{
  $em = $this->getDoctrine()->getManager();
  $em->persist($entity);
  $em->flush();

  return $this->redirect($this->generateUrl('target page'));

} catch(\Doctrine\ORM\ORMException $e){
  // flash msg
  $this->get('session')->getFlashBag()->add('error', 'Your custom message');
  // or some shortcut that need to be implemented
  // $this->addFlash('error', 'Custom message');

  // error logging - need customization
  $this->get('logger')->error($e->getMessage());
  //$this->get('logger')->error($e->getTraceAsString());
  // or some shortcut that need to be implemented
  // $this->logError($e);

  // some redirection e. g. to referer
  return $this->redirect($this->getRequest()->headers->get('referer'));
} catch(\Exception $e){
  // other exceptions
  // flash
  // logger
  // redirection
}

return $this->render('MyTestBundle:Article:new.html.twig', array(
  'entity' => $entity,
  'form'   => $form->createView(),
));


No comments:

Post a Comment