【问题标题】:symfony2 and throwing exception errorsymfony2 并抛出异常错误
【发布时间】:2012-05-24 10:13:32
【问题描述】:

我正在尝试抛出异常,我正在执行以下操作:

use Symfony\Component\HttpKernel\Exception\HttpNotFoundException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

然后我以下列方式使用它们:

 throw new HttpNotFoundException("Page not found");
   throw $this->createNotFoundException('The product does not exist');

但是我遇到了诸如 HttpNotFoundException is not found 之类的错误。

这是抛出异常的最佳方式吗?

【问题讨论】:

  • 抛出它们作为你的第一个例子是正常的, throw new Exception('Message');只要您像使用 use 语句那样导入了异常类,它就应该可以工作。可能还有更多您没有展示的内容 - 您可以发布您的实际类头和异常堆栈跟踪吗?
  • 我得到的错误是:致命错误:在 /Users/jinni/Sites/symfony.com/src/Rest/UserBundle/Controller/DefaultController 中找不到类“Rest\UserBundle\Controller\HttpNotFoundException”。 php
  • 我在顶部包含了 use Symfony\Component\HttpKernel\Exception

标签: php exception symfony


【解决方案1】:

试试:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

throw new NotFoundHttpException("Page not found");

我觉得你有点倒退了:-)

【讨论】:

  • 不发送404状态
【解决方案2】:

如果它在控制器中,你可以这样做:

throw $this->createNotFoundException('Unable to find entity.');

【讨论】:

    【解决方案3】:

    在控制器中,您可以简单地这样做:

    public function someAction()
    {
        // ...
    
        // Tested, and the user does not have permissions
        throw $this->createAccessDeniedException("You don't have access to this page!");
    
        // or tested and didn't found the product
        throw $this->createNotFoundException('The product does not exist');
    
        // ...
    }
    

    在这种情况下,无需在顶部包含 use Symfony\Component\HttpKernel\Exception\HttpNotFoundException;。原因是你没有直接使用类,就像使用构造函数一样。

    在控制器之外,您必须指出可以找到该类的位置,并像往常一样抛出异常。像这样:

    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    
    // ...
    
    // Something is missing
    throw new HttpNotFoundException('The product does not exist');
    

    use Symfony\Component\Security\Core\Exception\AccessDeniedException;
    
    // ...
    
    // Permissions were denied
    throw new AccessDeniedException("You don't have access to this page!");
    

    【讨论】: