php - 如何在 symfony 2 中捕获异常?

标签 php symfony

如何在 Controller 中捕获异常并在 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 block 中做什么?

最佳答案

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

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

关于php - 如何在 symfony 2 中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20325746/

相关文章:

forms - 删除来自空集合表单项的空值

php - Symfony3 - 从 yaml 文件动态下拉

php - magento从1.4.0.1升级到1.4.2.0

php - .htaccess 使 URL 对搜索引擎友好

php - 我的部分模板或 html 消失了。为 Prestashop 1.7.6.1、php 7.1.9 创建模块

php - 如何自动创建 key (如 FBAppid)进行注册?

php - 解析用于与 API 交互的 HTTP 状态代码

php - Symfony2 - 访问被拒绝(用户未完全验证)

php - SQLSTATE[08001] : [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it

mysql - Doctrine 2 : query using NativeQuery and ResultSetMapping