jfrqng
Last Updated: February 25, 2016
·
7.756K
· andreia
Mesr

Symfony2: Catch exception in the controller and show flash message

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

    $this->get('session')->setFlash('notice', 'Article inserted!');
    return $this->redirect($this->generateUrl('article_show', array('id' => $entity->getId())));
}catch(\Exception $e){
    // log $e->getMessage()
    $this->get('session')->setFlash('error', 'Can't insert the article.');
}

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

2 Responses
Add your response

3388
C636c24e8d4ea2d70460f72501d60c31

This is actually bad code, You should never (almost) catch \Exception, everything has it's own exception, catch them. and handle just those ones.
You should log all the exceptions that you catch as well, to know what went wrong.

over 1 year ago ·
5752
736212 10200976756252420 836055407 o

@devalien you're absolutely right!

over 1 year ago ·