php 如何在 symfony 2 中捕获异常?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20325746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch Exception in symfony 2?
提问by Swass
How to Catch exception in the controller and show flash message 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(),
));
What should I do in the catchblock?
我应该在catch街区做什么?
回答by Kamil Adryjanek
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(),
));
}
回答by Chathushka
Read this carefully, Catching exceptions and generating an output in the twig is clearly decribed here. :)
仔细阅读这里,这里清楚地描述了在树枝中捕获异常并生成输出。:)
http://symfony.com/doc/current/book/controller.html
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);

