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:

  1. 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)
  2. 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.
  3. 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?

    1 answer 1

    Describe some intricate steps. In symfony, there is a standard way: define a listener for the kernel.exception event. This event handles all exceptions thrown inside AppKernel::handle() .

    It can handle any exception as you wish. An example of such processing can be found in the official symfony documentation .

    • But I need to handle exceptions from listeners and continue working, and this will be impossible if we use this solution - AmsTaFFix