1

如何在 Symfony2 的存储库类中使用“NotFoundException”?

$test = $em->getRepository('DemoBundle:Test')->find(1);

if (!$test) {
    throw $this->createNotFoundException('The category area does not exist. Id 1');
}
4

2 回答 2

2

如果您想在查询没有结果时抛出适当的异常(in/inside/within)您的存储库。然后你应该使用Doctrine\ORM\NoResultException

顺便说一句,您共享的代码片段不应在您的存储库中使用。

于 2013-09-26T09:56:00.867 回答
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 %}
于 2013-09-26T14:56:13.883 回答