25

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

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 is not found 之类的错误。

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

4

3 回答 3

51

尝试:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

throw new NotFoundHttpException("Page not found");

我认为你有点倒退了:-)

于 2012-05-16T23:05:05.753 回答
9

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

throw $this->createNotFoundException('Unable to find entity.');
于 2012-07-13T10:58:32.523 回答
1

在控制器中,您可以简单地执行以下操作:

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!");
于 2016-01-29T15:53:08.113 回答