自定义ExceptionListener不捕获ConnectionException

时间:2016-12-16 21:26:41

标签: php symfony events

我想在我的Symfony 2项目中捕获Doctrine\DBAL\Exception\ConnectionException。我使用错误的数据访问参数进行测试。

为此,我创建了一个自定义的ExceptionListener。 这是我的班级:

namespace Namespace\Event;

use Doctrine\DBAL\Exception\ConnectionException;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Log\LoggerInterface;

class ExceptionListener
{

    private $logger;

    private $templateEngine;

    public function __construct(LoggerInterface $logger, EngineInterface $templateEngine)
    {
        $this->logger = $logger;
        $this->templateEngine = $templateEngine;
    }

    /**
     * @param GetResponseForExceptionEvent $event
     * @return void
     */
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof ConnectionException) {
            //...
        }
 }

这是我的问题,永远不会调用My ExceptionListener对象。这是我在services.yml中配置监听器的配置。

我的AppBundle\Resources\config\services.yml位于我的文件顶部。

app.exception.exception_listener:
    class: Namespace\Event\ExceptionListener
    arguments: [ '@logger', '@templating' ]
    tags:
      - { name: kernel.event_listener, event: kernel.exception }

我有一个错误堆栈:

An exception occured in driver: SQLSTATE[HY000] [2002] No route to host

但是,如果我看一下堆栈跟踪,我的监听器就会被调用:

at Container->get('app.exception.exception_listener') in classes.php line 1957
at ContainerAwareEventDispatcher->lazyLoad('kernel.exception') in classes.php line 1925
at ContainerAwareEventDispatcher->getListeners('kernel.exception') in TraceableEventDispatcher.php line 245
at TraceableEventDispatcher->preProcess('kernel.exception') in TraceableEventDispatcher.php line 135
at TraceableEventDispatcher->dispatch('kernel.exception', object(GetResponseForExceptionEvent)) in HttpKernel.php line 221
at HttpKernel->handleException(object(ConnectionException), object(Request), '1') in HttpKernel.php line 75
at HttpKernel->handle(object(Request), '1', true) in ContainerAwareHttpKernel.php line 69
at ContainerAwareHttpKernel->handle(object(Request), '1', true) in bootstrap.php.cache line 1505
at Kernel->handle(object(Request)) in app_dev.php line 42

这是php app/console debug:event-dispatcher kernel.exception

的输出
Registered Listeners for "kernel.exception" Event
Order   Callable
Priority
#1      Namespace\Event\ExceptionListener::onKernelException()
0
#2   Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException()
#3      Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException()

-128

1 个答案:

答案 0 :(得分:0)

您没有准确指定onKernelException方法中发生的事情。

确保它在事件中设置响应。例如,要重定向到URL:

 $response = new RedirectResponse('/some_url');
 $event->setResponse($response);
 return true;