如何在Symfony2中的倉庫類中使用「NotFoundException」?如何在symfony2中的倉庫類中獲取控制器對象
$test = $em->getRepository('DemoBundle:Test')->find(1);
if (!$test) {
throw $this->createNotFoundException('The category area does not exist. Id 1');
}
如何在Symfony2中的倉庫類中使用「NotFoundException」?如何在symfony2中的倉庫類中獲取控制器對象
$test = $em->getRepository('DemoBundle:Test')->find(1);
if (!$test) {
throw $this->createNotFoundException('The category area does not exist. Id 1');
}
如果你想拋出適當例外(中/中/中)你當你的查詢沒有結果庫。那麼你應該使用Doctrine\ORM\NoResultException。
順便說一下,您共享的代碼片段不應該在您的存儲庫中使用。
從文檔中,這裏是一個代碼示例: $ query = $ em-> createQuery('SELECT ...') - > setMaxResults(1); 嘗試{ $ product = $ query-> getSingleResult(); (\ Doctrine \ Orm \ NoResultException $ e){ $ product = null; } – Acyra
另一種方式進行錯誤處理使用會話錯誤,如
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 %}
爲什麼不在控制器動作中做到這一點? – pbenard