3

有什么办法可以服务在 EVENT_DISPATCH 侦听器中引发的异常?

class Module
{
    public function onBootstrap(EventInterface $event)
    {
        $application    = $event->getTarget();
        $eventManager   = $application->getEventManager();

        $eventManager->attach(MvcEvent::EVENT_DISPATCH, function(MvcEvent $event) {
            throw new ForbiddenException("403 - Fobidden");
        });
    }
}

我有一种常见的服务方式,ForbiddenException例如设置 403、返回 JSON 等……所有逻辑都附加到MvcEvent::EVENT_DISPATCH_ERROR侦听器。如何转移ForbiddenException到调度错误侦听器中的侦听器?从调度侦听器中抛出它会导致未捕获的异常错误......

任何帮助或提示如何克服它将不胜感激!

4

2 回答 2

2

如果我对您的理解正确,您希望附加到EVENT_DISPATCH_ERROR事件的侦听器来处理您提出的异常。

为此throw,您应该使用异常实例作为其参数之一自己触发调度错误事件,而不是仅仅触发异常,例如...

class Module
{
    public function onBootstrap(EventInterface $event)
    {
        $application    = $event->getTarget();
        $eventManager   = $application->getEventManager();

        $eventManager->attach(MvcEvent::EVENT_DISPATCH, function(MvcEvent $event) use ($eventManager) {
            // set some identifier for your error listener to look for
            $event->setError('forbidden');
            // add an instance of your exception
            $event->setParam('exception', new ForbiddenException("403 - Fobidden"));
            // trigger the dispatch error with your event payload
            $eventManager->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $event);
        });
    }
}

一旦触发你的错误监听器应该接管并处理你的异常

于 2016-08-10T18:29:36.267 回答
2

您应该使用 sharedevent manager 来绑定事件。像这样 :

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

    $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();
    $sm = $e->getApplication()->getServiceManager();
    $sharedManager->attach(
         'Zend\Mvc\Application', 
         'dispatch.error',
         function($e) use ($sm) {
            //Do what you want here
         }
    );
}

一旦匿名函数像这样工作,我建议用一个可调用的类替换它。

于 2016-08-10T09:03:51.953 回答