如何在symfony 2中捕获Exception? [英] How to catch Exception in symfony 2?
本文介绍了如何在symfony 2中捕获Exception?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在控制器中捕获异常并在Symfony 2中显示Flash消息?
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(),
));
我应该在catch
块中做什么?
推荐答案
您应注意可能引发的异常:
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(),
));
}
这篇关于如何在symfony 2中捕获Exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文