Xaris Rg
Xaris Rg

Reputation: 73

Problem loading view on EVENT_RENDER_ERROR

I am new to ZF2 and it seems like I cannot do what I intended to.

The project I work on occasionally get some PDO Exceptions that I cannot catch at the moment so I want to have a generic function upon application load that will load a custom error page when such an exception occurs.

The 'exception_template' in global.php is not loaded when those exceptions happen so I created a function which I call upon EVENT_RENDER_ERROR where I basically want to load this view.

I tried things like:

$redirect_view = new ViewModel();
$redirect_view->setTemplate('error/exception');

also tried this:

$e->setViewModel()->clearChildren();
$e->setViewModel()->addChild($redirect_view);
$e->stopPropagation(true);

But I either get this error:

[06-May-2019 15:11:19 Europe/Berlin] PHP Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'Zend\View\Renderer\PhpRenderer::render: Unable to render template "exception" ; resolver could not resolve to a file' in /var/www/vhosts/vendor/zendframework/zendframework/library/Zend/View/Renderer/PhpRenderer.php:499

or this:

#0 /var/www/vhosts/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php(83): Dashboard\Controller\InboxController->listAction()
#1 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))

I just want to load a plain view in case an unexpected error occurs throughout the entire project.

Thank you in advance.

Upvotes: 0

Views: 87

Answers (1)

Marcel
Marcel

Reputation: 5119

You can define a custom error template for your module in different ways. The most common - and in my eyes easier way - is the approach by defining the template in the module.config.php file of your module.

return [
    'controllers' => [ 
        /* your controllers here */
    ],
    'routes' => [
        /* your routes go here */
    ],
    'view_manager' => [
        'exception_template' => 'error/exception',
        'template_map' => [
            'error/exception' => __DIR__ . '../view/error/exception.phtml'
        ],
        'template_path_stack' => [
            __DIR__ . '../view',
        ],
    ],
];

As you can see, you can add an individuel template through the template_map option. Additionally add a new path to the template path stack and zend framework will walk the stack until the exception template is found.

Upvotes: 1

Related Questions