ZF3 / 2 - how to catch an exception thrown into the EVENT_DISPATCH listener?

Is there any way I can serve the exception thrown in the EVENT_DISPATCH listener?

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"); }); } } 

I have a general way of serving ForbiddenException as setting 403 returning JSON etc. All logic is tied to the MvcEvent::EVENT_DISPATCH_ERROR listener. How to pass ForbiddenException listener inside the listener of send errors? Throwing it from the dispatcher-receiver causes an exception reset error ...

Any help or advice on how to overcome this will be appreciated!

+2
source share
2 answers

you need to use the sharedevent manager to bind the event. Like this:

 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 } ); } 

I suggest replacing an anonymous function with a class with a call as soon as it works.

+1
source

If I understand you correctly, you want the listener to connect to the EVENT_DISPATCH_ERROR event to handle the exception you raise.

To do this, instead of simply throw exception, you should trigger the send error event yourself with an instance of your exception as one of its parameters, for example ...

 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); }); } } 

after starting your error listener should take over and handle your exception

+1
source

Source: https://habr.com/ru/post/1494320/


All Articles