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(),
));
Written by Andréia Bohner
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Php
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#