我正在尝试抛出异常而我正在执行以下操作:
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等。
这是抛出异常的最佳方式吗?
答案 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!");