Exception handling in the MVC - best practics

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:

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 => [
            JsonModel::class => [
        $view = $this->acceptableViewModelSelector($view_accept_criteria);

        try {
        } catch (\Exception $e) {
                "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:

  1. Logging
  2. 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?


You can extends Laminas\Mvc\Application class and implements for example like that function:

public function run()
    try {
       return parent::run();
    } catch (Exception $e) {
      //your logic error handling

And call it for public/index.php