How to use default layout for error pages instead of errorXXX views

The issue is covered in "The Definite Guide to Yii" (Error Handling - Handling Errors Using an Action).

First we need to adjust application configuration as follows:

return array(

Here in the line "'errorAction'=>'mycontroller/error'" we define controller and its action, which should be used in case of an error ('mycontroller' - the controller, 'error' - the action).

Next we define 'error' action in 'mycontroller' controller:

public function actionError()
    $error = Yii::app()->errorHandler->error;
    if ($error)
	$this->render('error', array('error'=>$error));
	throw new CHttpException(404, 'Page not found.');

Here if the action is triggered by an error we render 'error' view of 'mycontroller' ('/protected/views/mycontroller/error.php'), if not - we trigger 404 error manually.

The last step is to setup our error view. It could be as follows:

<?php $this->pageTitle=Yii::app()->name . ' - ' .$error['code']; ?>
<h2>Error <?php echo $error['code'] ?></h2>
    <?php echo $error['message']; ?>

Now all application errors are rendered using the default application layout.

4 0
Viewed: 30 383 times
Version: 1.1
Category: Tutorials
Written by: idle sign
Last updated by: Yang He
Created on: Sep 23, 2009
Last updated: 5 years ago
Update Article


View all history