We have an EventDispatcher, which we use as follows
$this->eventDispatcher->dispatch('order.after.creation', new OrderAfterCreationEvent($subOrder)); Subscribe to this event in services.yml
listener.orderCreation: class: ...\Listener\OrderCreationListener arguments: [...] tags: - { name: kernel.event_listener, event: order.after.creation, method: onOrderCreation } And this listener is quite complicated and throws an exception.
class OrderCreationListener extends AbstractListener { public function onOrderCreation(OrderAfterCreationEvent $event) { throw new \Exception(); } } And now the main question is how best to catch such exceptions? Several ideas come to mind:
- frame the Listener code in try {} catch and then he decides how to act, but there are careless programmers who can add their Listener without framing it in try {} catch, and then we get an unhandled exception that will break the properly worked code (order creation)
- frame the dispatch method in try {} catch. But then one line turns into a few, and if you need to handle exceptions? Then, in general, the darkness ... And even more so it is necessary to do everywhere, as a negligent programmer can also forget. And also with the exclusion of the first Listener, all the other Listeners will not work.
- inherit from ContainerAwareEventDispatcher and override the doDispatch method
ContainerAwareEventDispatcher :: doDispatch ()
protected function doDispatch($listeners, $eventName, Event $event) { foreach ($listeners as $listener) { call_user_func($listener, $event, $eventName, $this); if ($event->isPropagationStopped()) { break; } } } new doDispatch ()
protected function doDispatch($listeners, $eventName, Event $event) { foreach ($listeners as $listener) { try { call_user_func($listener, $event, $eventName, $this); } catch (\Exception $e) { // handle and log $e } if ($event->isPropagationStopped()) { break; } } } As a result, we will get universal exception handling from the Listeners, but we will redefine the method and will be forced to support it.
I'm more inclined to the 3rd decision. But maybe I missed something, tell me how you solve this problem?