【问题标题】:How to throw exception from EVENT_DISPATCH event in ZF2如何从 ZF2 中的 EVENT_DISPATCH 事件中引发异常
【发布时间】:2014-03-12 09:44:51
【问题描述】:

我想从EVENT_DISPATCH 事件中抛出一个异常,该异常的处理方式与从控制器调度方法中抛出该异常的方式相同。但是我不知道该怎么做。

在第一段代码中,没有捕获到异常,也没有触发 EVENT_DISPATCH_ERROR。我尝试使用MvcEvent::setError 方法,但没有任何线索。

$this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH, array($this, 'onDispatch'), 100);


public function onDispatch(MvcEvent $e)
{
    if ($condition) {
        throw SomeException;
    }
}

class Controller extends AbstractActionController
{
    public function onDispatch(MvcEvent $e)
    {
        if ($condition) {
            throw SomeException;
        }
    }
}

【问题讨论】:

  • Roel,你找到捕捉这些异常的方法了吗?我也在为在调度事件中引发异常而苦苦挣扎。
  • 我没有。这是不可能的。请参阅下面的帖子。

标签: php zend-framework2 listener


【解决方案1】:

公共函数 onDispatch(MvcEvent $e) { 如果($条件){ $e->getTarget()->getEventManager()->trigger('dispatch.error', $e); } }

哦,对不起,我的错,'dispatch.error'只能在调度之前触发,我在onRoute事件中做到了。

但是如果你想在调度事件中抛出异常试试这个,它对我有用:

重要提示:优先级应该是一个负值,这样才能正常工作

$em->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', array($this, 'onDispatch'), -100);

public function onDispatch(MvcEvent $e)
{
    throw new \Exception('This is Exception');
}

【讨论】:

  • 这似乎不起作用。当我将此代码放在调度侦听器中时,什么都没有发生。此外,不会以任何方式传递异常。
  • 这在我的情况下不起作用。抛出异常,但不会被框架捕获,因此不会触发 EVENT_DISPATCH_ERROR 事件。即使是负面优先级。
【解决方案2】:

我不确定您尝试做的事情是否 100% 可能。不过,你可以靠近。

问题源于 ZF2 将控制器异常作为事件处理,而事件管理器决定如何处理这些异常。由于您从事件管理器本身引发异常,因此无法以与控制器异常相同的方式处理它。

一种可能的解决方案是在 php 中设置一个全局异常处理程序:

public function onBootstrap( MvcEvent $e )
{
    $eventManager = $e->getApplication()->getEventManager();
    $eventManager->attach( MvcEvent::EVENT_DISPATCH, array( $this, 'onDispatch' ) );

    //set the global exception handler
    set_exception_handler( array( $this, 'handleException' ) );
}

public function onDispatch( MvcEvent $e )
{
    if ( true )
    {
        throw new \Exception();
    }
}

public function handleException( \Exception $e )
{
    //do something with the exception
}

但是,采用这种方法有一些缺点,因为这会覆盖应用程序中所有异常的默认处理,因此您可能希望只允许它处理特定异常并让默认处理程序支持其余的,所以:

public function handleException( \Exception $e )
{
    if ( $e instanceof MyExceptionClass )
    {
        //do something with the exception
    }
    else
    {
        //rethrow the exception
        throw $e;
    }
}

有关这方面的更多信息,您可以阅读 php 文档中的 cmets:http://php.net/manual/en/function.set-exception-handler.php#usernotes

【讨论】:

  • 感谢您解释为什么这不能在 ZF2 中完成。我会给你积分。
【解决方案3】:

在 Module.php 中尝试类似的方法

public function onBootstrap(MvcEvent $e)
{
    $eventManager = $e->getApplication()->getEventManager();

    $eventManager->attach( \Zend\Mvc\MvcEvent::EVENT_DISPATCH, array($this,'onDispatch'), 100 );

}

public function onDispatch(MvcEvent $e)
{
    if ($condition) {
        throw SomeException;
    }
}

【讨论】:

  • 显然我注册了我在模块的Bootstrap方法中提到的监听器。
猜你喜欢
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 2020-05-20
  • 2013-09-14
  • 2012-11-11
  • 1970-01-01
  • 2016-12-15
  • 2012-03-14
相关资源
最近更新 更多