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 }
Symfony\Component\HttpKernel\EventListener\EventListener:50) and if you're throwing an exception in theonRequestmethod this exception won't be handled properly by the default exception controller (Symfony\Bundle\TwigBundle\Controller\ExceptionController:showAction). If you want full control on exception handling I'd look into implementing your custom exception listener. If you just want to return something directly fromonRequestyou can use$event->setResponse()to stop propagation and return your response.