Hello!
I have a very simple, at first glance, question, but I have been sitting and thinking about it for several weeks now and I just can’t realize it.
Probably this is due to a misunderstanding of some fundamental things that I cannot find anywhere about the Laminas MVC project.
So, in my project, there is a model that looks like this:
My Model:
declare(strict_types=1);
namespace MyModelName\Service;
class MyClass {
public function myFunction()
{
// for example
$check_it = false;
if (true != $check_it) {
throw new \Exception('Oh, thats wrong');
}
}
}
Also, I have a controller
My Controller:
class MyController extends AbstractActionController
{
public function indexAction()
{
$my_class = new MyClass();
$view_accept_criteria = [
ViewModel::class => [
'text/html',
'application/xhtml+xml',
],
JsonModel::class => [
'application/json',
'application/javascript',
],
],
$view = $this->acceptableViewModelSelector($view_accept_criteria);
try {
$my_class->myFunction();
} catch (\Exception $e) {
$view->setVariables([
"success" => false,
"errorMessage" => $e->getMessage(),
}
return $view;
}
So what’s the problem? And the problem is that I just can’t figure out where and how I can catch the exception in order to handle it not at the controller level, but at the module level, for all exceptions in general, well, at least in order to:
- Logging
- Select a rendering method (JsonModel or ViewModel)
If they do this at the controller level, everything is simple and clear, but I would like some universality, namely, so that you can catch exceptions about any errors in general (at least at the level of one module).
Probably I need to dig to the side and do something in Module.php in the onDispatch function or maybe MvcEvent::EVENT_DISPATCH_ERROR
Are there any best practices in this matter?