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.
User Contributed Notes 1
Note
If you want to handle errors in SiteController, then in config it should be 'errorAction'=>'site/error', and path to view is '/protected/views/site/error.php'
Also, if you are using 'backend' as admin area, then copy view file to '/protected/backend/views/site/error.php' and actionError() function to protected/backend/controllers/SiteController.php
Thanks for this great cookbook article. Yii makes so easy to handle complicated things!
Leave a comment
If you have any questions, please ask in the forum instead.
Join the conversation to share a note.