symfony2并抛出异常错误

时间:2012-05-16 19:37:15

标签: php exception symfony

我正在尝试抛出异常而我正在执行以下操作:

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等。

这是抛出异常的最佳方式吗?

4 个答案:

答案 0 :(得分:49)

尝试:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

throw new NotFoundHttpException("Page not found");

我认为你有点倒退: - )

答案 1 :(得分:29)

在任何控制器中,您可以将其用于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

答案 2 :(得分:10)

如果它在控制器中,你可以这样做:

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

答案 3 :(得分: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!");