【问题标题】:How to catch Exception in symfony 2?如何在 symfony 2 中捕获异常?
【发布时间】:2013-12-02 10:16:11
【问题描述】:

如何在控制器中捕获异常并在 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 块中做什么?

【问题讨论】:

  • toString($e) 不工作。它显示 FatalErrorException: Error: Call to undefined function toString()
  • echo (string)$e; 或更好,在高效网站上向您发送电子邮件:mail('you@x.com', 'Exception in script ...', var_export($e, true));

标签: php symfony


【解决方案1】:

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

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 起已删除。请考虑进行一些编辑
【解决方案2】:

仔细阅读,Catching exceptions and generate an output in the twig 在这里清楚地描述了。 :)

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

进一步,

你可以使用这个原始方法来获取一个类的方法:

print_r(get_class_methods($e))

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    • 2011-04-03
    • 2021-03-26
    • 2013-09-04
    相关资源
    最近更新 更多