2012-05-16 109 views
17

我想拋出異常,我做了以下內容:Symfony2中,並拋出異常錯誤

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未找到等。

這是拋出異常的最佳方式嗎?

+1

是很正常的把他們作爲你的第一個例子,拋出新的異常( '信息');只要你導入了異常類,就像你使用use語句做的那樣,它應該可以工作。可能更多的這一點,你沒有顯示 - 你可以發佈你的實際類頭和異常堆棧跟蹤? – PorridgeBear

+0

我得到的錯誤是:致命錯誤:類'Rest \ UserBundle \ Controller \ HttpNotFoundException'找不到/Users/jinni/Sites/symfony.com/src/Rest/UserBundle/Controller/DefaultController.php – jini

+0

我已經包括使用Symfony \ Component \ HttpKernel \ Exception頂部 – jini

回答

45

嘗試:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 

throw new NotFoundHttpException("Page not found"); 

我覺得你得到它有點倒退:-)

+0

感謝Chris ... – jini

+0

感謝@Chris,工作得像一個魅力 – Stevanicus

+0

它不發送404狀態 – Volatil3

9

如果它的控制器,你可以這樣說:

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

在任何控件LER可以使用該對內部的Symfony 404的HTTP響應

throw $this->createNotFoundException('Sorry not existing'); 

相同

throw new NotFoundHttpException('Sorry not existing!'); 

或此爲500的HTTP響應代碼

throw $this->createException('Something went wrong'); 

相同

throw new \Exception('Something went wrong!'); 

//in your controller 
$response = new Response(); 
$response->setStatusCode(500); 
return $response; 

或這是任何類型的錯誤

throw new Symfony\Component\HttpKernel\Exception\HttpException(500, "Some description"); 

而且...對於自定義異常you can flow this URL

+1

更好.. nuff說。 – JohnnyQ

+2

@ hassan-magdy,我無法在任何類的symfony 2.3,2.7或3.0中找到「createException(...)」方法。你確定它有效嗎? –

+0

@NunoPereira最好的解決方案應該拋出一個新的[HTTPException](http://api.symfony.com/3.2/Symfony/Component/HttpKernel/Exception/HttpException.html#method___construct),如上面最後一個示例中所述。 – sentenza

0

在控制器,你可以簡單地做:

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!");