处理所有抛出的异常,用ZF2放入flashMessage [英] Handle all exceptions thrown, put them into flashMessage with ZF2
问题描述
我需要正确捕获所有在我的 ZF2 服务中抛出的异常并将消息返回给用户的 flashMessage.
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));
}
这就像一个魅力,但我不确定在控制器中这样做是否好,如果这是实现这一目标的更好/干净的方式.也许一个事件可以处理这个并创建一个带有 $e->getMessage()
的 flash 消息.
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 ?
推荐答案
您可以在 Module.php
中捕获应用程序的所有异常.当在您的 onBootstrap
方法中创建一个事件时,您可以附加一个函数来处理抛出的执行.
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());
}
在您的视图中(主要在 layout.phtml
中):
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
希望这会有所帮助.
这篇关于处理所有抛出的异常,用ZF2放入flashMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!