Lucas
Lucas

Reputation: 21

Symfony2 uncaught exception inside Event Listener

I have a problem with throwing Symfony 2 exception inside event listner. When I do it I get Uncaught exception (onRequest method of listener). Is there any way to throw exception in listener that can be caught by Symfony.

I was trying to avoid this problem by changing the controller in case of an exception (onController method of listener). Target controller had just one line:

throw $this->createNotFoundException('Test');

The controller swap worked but it also resulted in uncaught exception error.

How to wrap a listener or swapped controller inside symfony exception catcher.

My listener:

namespace AppBundle\Listener;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Controller\HomeController;

class SessionListener {

    private $container;

    public function __construct($container)
    {
        $this->container = $container;
    }

    public function onController(FilterControllerEvent $event)
    {
        $controller=new HomeController();

        $replacementController= array($controller, 'notFoundAction');

        $event->setController($replacementController);
    }

    public function onRequest(Event $event) {
        $session = $this->container->get('session'); 
        $kernel = $this->container->get('kernel');

        throw new NotFoundHttpException('Test');
    }

}

My services.yml

services:
    app.session_listener:
        class: AppBundle\Listener\SessionListener
        arguments: [@service_container]    
        tags:
         - { name: kernel.event_listener, event: kernel.request, method: onRequest }
         - { name: kernel.event_listener, event: kernel.controller, method: onController } 

Upvotes: 2

Views: 2110

Answers (2)

gblock
gblock

Reputation: 604

As an alternative you can return a 404 response instead of throwing an exception:

class SessionListener
{
    public function onRequest(GetResponseEvent $event)
    {
        $event->setResponse(new Response('Test', 404));
    }
}

Upvotes: 0

morpheus0010
morpheus0010

Reputation: 131

probably with a try catch

public function onRequest(Event $event) {

 try{

  $session = $this->container->get('session'); 
  $kernel = $this->container->get('kernel');

 }catch(NotFoundHttpException ex){

  throw new NotFoundHttpException('Test');

 }




}

Upvotes: 1

Related Questions