在控制器中,您可以简单地执行以下操作:
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!");