如何在symfony 2中捕获异常


How to catch Exception in symfony 2?

如何在控制器中捕获异常并在Symfony 2中显示flash消息?

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

我应该在catch块中做什么?

您应该注意可能引发的异常:

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

仔细阅读,这里明确描述了捕获异常并在树枝中生成输出。:)

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

此外,

您可以使用这个基元方法来获取类的方法:

print_r(get_class_methods($e))

或者这个来漂亮地打印你的对象

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