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 ?
You could catch all your application's exceptions in your
Module.php
. When an event is created in youronBootstrap
method, you can attach a function which will handle the thrown execption.So you'll have something like this:
In your views (mostly in
layout.phtml
) :May be you could also see this intersting post
Hope this could help.
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