Handle all exceptions thrown, put them into flashM

2019-08-02 19:44发布

问题:

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 ?

回答1:

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

Hope this could help.



回答2:

You're basically asking if it's better to put the logic in the action of the controller or handling this controller/application wise.

I'd say in the action is fine, because eventually there may be some cases (now or in the future) where you need to handle the error/exception in a different way in another part of the application