我正在尝试抛出异常,我正在执行以下操作:
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等。
这是引发异常的最佳方式吗?
尝试:
use Symfony'Component'HttpKernel'Exception'NotFoundHttpException;
和
throw new NotFoundHttpException("Page not found");
我想你有点倒退了:-)
如果它在控制器中,你可以这样做:
throw $this->createNotFoundException('Unable to find entity.');
在控制器中,您可以简单地执行以下操作:
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!");