Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to Catch exception in the controller and show flash message in Symfony 2?

try{
  $em = $this->getDoctrine()->getManager();
  $em->persist($entity);
  $em->flush();

  return $this->redirect($this->generateUrl('target page'));
} catch(Exception $e){
  // What to do in this part???
}

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

What should I do in the catch block?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
581 views
Welcome To Ask or Share your Answers For Others

1 Answer

You should take care for the exceptions that could be raised:

public function postAction(Request $request)
{
  // ...

  try{
    $em = $this->getDoctrine()->getManager();
    $em->persist($entity);
    $em->flush();

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

  } catch(DoctrineORMORMException $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($request->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(),
  ));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...