2013-09-26 22 views

回答

2

如果你想拋出適當例外(中/中/中)你當你的查詢沒有結果庫。那麼你應該使用Doctrine\ORM\NoResultException

順便說一下,您共享的代碼片段不應該在您的存儲庫中使用。

+0

從文檔中,這裏是一個代碼示例: $ query = $ em-> createQuery('SELECT ...') - > setMaxResults(1); 嘗試{ $ product = $ query-> getSingleResult(); (\ Doctrine \ Orm \ NoResultException $ e){ $ product = null; } – Acyra

1

另一種方式進行錯誤處理使用會話錯誤,如

try { 
      $em = $this->getDoctrine()->getManager(); 
      $entity = $em->getRepository('product')->find($id); 

      if (!$entity) { 
       $this->get('session')->setFlash('warning', 'Unable to find Product.'); 
      } 

      $em->remove($entity); 
      $em->flush(); 
      $this->get('session')->setFlash('success', 'Product Detail has been deleted.'); 
      return $this->redirect($this->generateUrl('admin_products')); 
     } catch (\Doctrine\DBAL\DBALException $e) { 
      $this->get('session')->setFlash(
        'warning', 'This Product cannot be deleted!' 
      ); 
      return $this->redirect($this->getRequest()->headers->get('referer')); 
     } 
    } 

而且在下面給出代碼的樹枝模板使用。

{% if app.session.hasFlash('success') %} 
    <div class="alert alert-success"> 
    {{ app.session.flash('success') }} 
     </div> 

{% endif %} 
    {% if app.session.hasFlash('warning') %} 
     <div class="alert alert-error"> 
    {{ app.session.flash('warning') }} 
      </div> 

{% endif %} 
相關問題