Klaus Silveira
Contributed by Klaus Silveira in #9405

Do you know the difference between Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException and Symfony\Component\Security\Core\Exception\AccessDeniedException?

Their names look very similar and both deal with resources for which the user does not have access. But which one should you use in a controller? This is probably counter-intuitive, but you should use Symfony\Component\Security\Core\Exception\AccessDeniedException. And when using an IDE, you might import the wrong exception pretty easily. As this is a frequent mistake, we even added a rule about this on SensioLabsInsight (and this violation is triggered quite often).

As of 2.5, you can now rely on a helper method that does the right thing (if you are using the Symfony\Bundle\FrameworkBundle\Controller\Controller base class):

1
throw $this->createAccessDeniedException('You cannot access this page!');

By the way, Symfony\Component\Security\Core\Exception\AccessDeniedException is the exception class you want to use because it is automatically caught by the Symfony Security Firewall, which generates the correct response for the user.

Published in #Living on the edge