有什么办法可以在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
传递给调度错误侦听器内的侦听器?从调度侦听器抛出它会导致Uncaught异常错误...
任何帮助或提示如何克服它将不胜感激!
答案 0 :(得分: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
}
);
}
我建议用一个可调用的类替换匿名函数。
答案 1 :(得分: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);
});
}
}
一旦触发,您的错误监听器就应该接管并处理您的异常