0

Using symfony 3.4, I have a service for custom Exception handling:

class CustomExceptionController extends ExceptionController
{
    [...]
}

Now I want to log the exception and with it the currently logged in user. Since I am not extending from a standard Controller I can't do the following:

$user = $this->get('security.token_storage')->getToken()->getUser();

So I found this question on Stackoverflow: How to get the current logged User in a service but for some reason when I inject TokenStorageInterface $tokenStorageinto the constructor, I get null when I call $tokenStorage->getToken().

What can be the reason for that? My services.yml looks as follows:

AppBundle\Controller\CustomExceptionController:
    public: true
    arguments: ["@twig", %kernel.debug%, "@doctrine.orm.log_entity_manager", '@security.token_storage']

and my controller like this:

public function __construct(Environment $twig, bool $debug, EntityManager $entityManager, TokenStorageInterface $tokenStorage)
{
    $this->em = $entityManager;
    $this->tokenStorage = $tokenStorage;
    parent::__construct($twig, $debug);
}

Did I miss something? I double-checked and the user is logged in. But I always get null when requesting the token.

Mathias Bader
  • 3,585
  • 7
  • 39
  • 61
  • My best guess would be that the token storage is filled **later** by a firewall (it's easy to confirm it with a debugger). Have you tried to call `$tokenStorage->getToken()` not in constructor but action instead? – zerkms Jun 07 '18 at 09:50
  • I cannot reproduce the bug, it does just work for me... can you please give us infos about **how** you do call this controller ? is this in twig's config that you've set it as `exception_controller` or do you call it manually ? – Webvoid Jun 07 '18 at 10:34

0 Answers0