事件监听器中的Symfony2未捕获异常

时间:2015-11-25 16:02:20

标签: symfony exception listener uncaught-exception

我在事件列表器中抛出Symfony 2异常时遇到问题。当我这样做时,我得到了Uncaught异常(onRequest方法的监听器)。有没有办法在侦听器中抛出异常,可以被Symfony捕获。

我试图通过在异常情况下更改控制器来避免此问题(onController方法的侦听器)。目标控制器只有一行:

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

控制器交换有效,但也导致未捕获的异常错误。

如何在symfony异常捕获器中包装侦听器或交换控制器。

我的听众:     

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

}

我的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 } 

2 个答案:

答案 0 :(得分:1)

可能是试一试

public function onRequest(Event $event) {

 try{

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

 }catch(NotFoundHttpException ex){

  throw new NotFoundHttpException('Test');

 }




}

答案 1 :(得分:0)

作为替代方案,您可以返回404响应,而不是抛出异常:

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