Zend 2定义控制器错误页面


Zend 2 define error page for controller

我有一个模块与几个控制器。除了一个控制器之外,我想对所有控制器使用正常的错误页面。

是否可以定义一个错误页,仅在某个控制器中抛出异常时使用?

这就是模块配置的样子:

'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',
        'layout/header'           => __DIR__ . '/../view/layout/header.phtml',
        'layout/footer'           => __DIR__ . '/../view/layout/footer.phtml',
        'layout/sidebar'          => __DIR__ . '/../view/layout/sidebar.phtml',
        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'pagination/sliding'      => __DIR__ . '/../view/pagination/sliding.phtml',
        'error/404'               => __DIR__ . '/../view/error/404.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
        __DIR__ . '/../view',
    ),
),

我知道我可以实现这样的东西通过把这个控制器在一个额外的模块,并为这个模块定义一个错误页面,但我不想拆分我的项目在几个模块。

找到了解决我问题的方法:

在template_map中定义错误模板:

    'template_map' => array(
          ...
          'error/controller'      => __DIR__ . '/../view/error/controller/index.phtml',
    ),

在控制器构造方法中设置模板:

public function __construct()
{  
      $this->getServiceLocator()->get('ViewManager')->getExceptionStrategy()->setExceptionTemplate('error/controller');
}