8

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?

3
  • stackoverflow.com/questions/5689415/… Commented Dec 2, 2013 at 10:26
  • toString($e) is not working. It shows FatalErrorException: Error: Call to undefined function toString() Commented Dec 2, 2013 at 10:32
  • echo (string)$e; or better, send you an email on a productive site: mail('[email protected]', 'Exception in script ...', var_export($e, true)); Commented Dec 2, 2013 at 10:42

2 Answers 2

16

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(\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($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(),
  ));
}
Sign up to request clarification or add additional context in comments.

1 Comment

getRequest is Deprecated as of Symfony 2.4 and Removed as of Symfony 3.0. Please consider some editing
3

Read this carefully, Catching exceptions and generating an output in the twig is clearly decribed here. :)

http://symfony.com/doc/current/book/controller.html

further,

you can use this primitive method to get methods of a class:

print_r(get_class_methods($e))

or this to pretty print your object

\Doctrine\Common\Util\Debug::dump($e);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.