phpzend-framework2http-status-code-404zend-framework-modules

Use the same error handler in different modules in Zend Framework 2


I have many modules in an Zend application. There will be errors and exceptions in every module, right? So I create the error page in the Application module, and it works.

However, in other modules, they can't use the error page. So what should I do to reuse the error page?

Here's the module.config.php file in Application module:

return array(
    ...,
    'controllers' => array(
        'invokables' => array(
            'Application\Controller\Index' => 'Application\Controller\IndexController'
        ),
    ),
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions'       => true,
        'doctype'                  => 'HTML5',
        'not_found_template'       => 'error/404',
        'exception_template'       => 'error/index',
        'template_map' => array(
            'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
            'error/404'               => __DIR__ . '/../view/error/404.phtml',
            'error/index'             => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

The problem occurs when I return a HTTP 404 response manually with following code:

if ( $information == null ) {
    $response = $this->getResponse();
    $response->setStatusCode(404);
    return $response;
}

However, when I access an illegal resources like http://example.com/something-do-not-exist. I will reach the 404 error page with the exception The requested URL could not be matched by routing.


Solution

  • The configuration you have listed is defined in the application module, however it is not specific to that module.

    This is because during the application bootstrap each module.config.php is merged together into one configuration array (using array_merge_recursive()). This is the configuration you can get using $serviceManager->get('Config');

    So the configuration is global to the application and all errors (exceptions) should use the same error template (application/view/error/index.phtml).

    Keep in mind however that the loading order of the modules is important; as modules loading last will always overwrite existing configuration.