2012-05-16 87 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!");