Last Updated: January 28, 2019
·
13.53K
· andreia

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(),
));

2 Responses
Add your response

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 ·

@devalien you're absolutely right!

over 1 year ago ·