在控制器,你可以簡單地做:
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