在控制器,你可以简单地做:
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!");
是很正常的把他们作为你的第一个例子,抛出新的异常( '信息');只要你导入了异常类,就像你使用use语句做的那样,它应该可以工作。可能更多的这一点,你没有显示 - 你可以发布你的实际类头和异常堆栈跟踪? – PorridgeBear
我得到的错误是:致命错误:类'Rest \ UserBundle \ Controller \ HttpNotFoundException'找不到/Users/jinni/Sites/symfony.com/src/Rest/UserBundle/Controller/DefaultController.php – jini
我已经包括使用Symfony \ Component \ HttpKernel \ Exception顶部 – jini