PHP-ZF3 / 2-如何捕获在EVENT_DISPATCH侦听器中引发的异常?
作者:互联网
有什么方法可以处理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传输到调度错误侦听器内的侦听器?将其从调度侦听器中抛出会导致未捕获的异常错误…
任何帮助或技巧如何克服它,将不胜感激!
解决方法:
您应该使用sharedevent管理器来绑定事件.像这样 :
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
}
);
}
我建议一旦这样工作,就将匿名函数替换为可调用类.
标签:zend-framework3,zend-framework2,php 来源: https://codeday.me/bug/20191026/1939222.html