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(
    ......
    'components'=>array(
        'errorHandler'=>array(
            'errorAction'=>'mycontroller/error',
        ),
    ),
);

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));
    else
	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>
<div>
    <?php echo $error['message']; ?>
</div>

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

4 0
3 followers
Viewed: 43 051 times
Version: 1.1
Category: Tutorials
Tags:
Written by: idle sign
Last updated by: Yang He
Created on: Sep 23, 2009
Last updated: 11 years ago
Update Article

Revisions

View all history