Search code examples
phparchitecturezend-framework2standards

Handle all exceptions thrown, put them into flashMessage with ZF2


I need to catch properly, all my exceptions thrown in my ZF2 services and return the message into a flashMessage to the user.

This is what i tried in my Controller action:

try {
    $newConfigID = $this->configService->updateConfig($form->getData());
} catch (\Exception $e) {
    $this->flashMessenger()->setNamespace('danger')->addMessage($e->getMessage());
    return $this->redirect()->toRoute('config/update', array('idConfig' => $idConfig));
}

This is working like a charm, but i'm not sure if it's good to do this in Controller, if it's the better/clean way to achieve this. Maybe an event can handle this and create a flash message with the $e->getMessage() into it.

Is this considered bad architecture ? If yes, how can i do this properly ?


Solution

  • You could catch all your application's exceptions in your Module.php. When an event is created in your onBootstrap method, you can attach a function which will handle the thrown execption.

    So you'll have something like this:

    //file : Module.php
    
    public function onBootstrap(MvcEvent $event)
    {
        $em= $event->getApplication()->getEventManager();
        $em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'handleException']);
        $em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, [$this, 'handleException']);
    }
    
    public function handleException(MvcEvent $event)
    {
        $e= $event->getParam('exception');
        $flashMessenger = new FlashMessenger();
        $flashMessenger->setNamespace('error');
        $flashMessenger->addMessage($e->getMessage());
    
        $event->getViewModel()->setVariable('flashMessages', $flashMessenger->getMessages());
       
    }
    

    In your views (mostly in layout.phtml) :

    <?php if(isset($flashMessages)) : ?>
    <ul class="errors">
        <?php foreach ($flashMessages as $flashMessage) : ?>
        <li><?php echo $flashMessage; ?></li>
        <?php endforeach; ?> 
    </ul>
    <?php endif; ?>
    

    May be you could also see this intersting post