如何在Symfony 2中捕获异常?

8
如何在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(),
));

catch块中应该做什么?


https://dev59.com/52025IYBdhLWcg3w_a6r - Asif
toString($e)不起作用。它显示FatalErrorException: Error: Call to undefined function toString()。 - Swass
echo (string)$e; 或者更好的方式是,在生产环境中发送电子邮件:mail('you@x.com', '脚本异常...', var_export($e, true)); - Daniel W.
2个回答

16

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

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

getRequestSymfony 2.4起已被弃用,并在Symfony 3.0中被删除。请考虑进行一些编辑。 - Peyman Mohamadpour

3
请仔细阅读,这里清楚地描述了在twig中捕获异常并生成输出的方法。 :) http://symfony.com/doc/current/book/controller.html 此外,
您可以使用这种原始方法来获取类的方法:
print_r(get_class_methods($e))

或者使用此方法将您的对象格式化输出
\Doctrine\Common\Util\Debug::dump($e);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接