处理抛出的所有异常,把它们放到flashMessage与ZF2 [英] 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-&GT即显信息;的getMessage()
进入它
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
方法,可以附加将处理抛出execption的功能。
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.
所以你有这样的事情:
//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; ?>
可能是你还可以看到这个野趣帖子
希望这可以帮助。
这篇关于处理抛出的所有异常,把它们放到flashMessage与ZF2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!