25

I am trying to throw exceptions and I am doing the following:

use Symfony\Component\HttpKernel\Exception\HttpNotFoundException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

I am then using them the following way:

 throw new HttpNotFoundException("Page not found");
   throw $this->createNotFoundException('The product does not exist');

however I am getting errors like HttpNotFoundException is not found etc.

Is this the best way to throw exceptions?

Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169
  • 1
    It's normal to throw them as your first example, throw new Exception('Message'); So long as you've imported the exception class as you seem to have done with a use statement it ought to work. Possibly more to this that you are not showing - can you post your actual class headers and exception stack trace? – PorridgeBear May 16 '12 at 20:01
  • 1
    error I get is: Fatal error: Class 'Rest\UserBundle\Controller\HttpNotFoundException' not found in /Users/jinni/Sites/symfony.com/src/Rest/UserBundle/Controller/DefaultController.php – Strong Like Bull May 16 '12 at 20:34
  • I have included use Symfony\Component\HttpKernel\Exception at top – Strong Like Bull May 16 '12 at 20:34

3 Answers3

53

Try:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

and

throw new NotFoundHttpException("Page not found");

I think you got it a bit backwards :-)

Chris McKinnel
  • 14,694
  • 6
  • 64
  • 67
9

If its in a controller, you can do it this way :

throw $this->createNotFoundException('Unable to find entity.');
Chopchop
  • 2,899
  • 18
  • 36
1

In the controller, you can simply do:

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');

    // ...
}

In this situation, there'se no need to include the use Symfony\Component\HttpKernel\Exception\HttpNotFoundException; at the top. The reason for that is that you're not using the class directly, like using the constructor.

Outside the controller, you must indicate where the class can be found, and throw an exception as you would normally do. Like this:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

// ...

// Something is missing
throw new HttpNotFoundException('The product does not exist');

or

use Symfony\Component\Security\Core\Exception\AccessDeniedException;

// ...

// Permissions were denied
throw new AccessDeniedException("You don't have access to this page!");
Nuno Pereira
  • 480
  • 4
  • 18