Error handling is very important to provide user friendly application. Yii provides an easy way to handle errors in organized and customized way. Yii has a component CErrorHandler which provides the functionality of error handling. Also yii provides a way to handle exception using CHttpException.
Default Error handling configuration
CErrorHandler named as errorHandler component. It has default action to site/error.
|
1 2 3 4 |
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
), |
site/error
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
} |
We can get error using Yii::app()->errorHandler->error or Yii::app()->errorHandler->getError(). Both return an array containing the error details.
Returned array elements:
- code – the HTTP status code (e.g. 403, 500)
- type – the error type (e.g. ‘CHttpException’, ‘PHP Error’)
- message – the error message
- file – the name of the PHP script file where the error occurs
- line – the line number of the code where the error occurs
- trace – the call stack of the error
- source – the context source code where the error occurs
You can customize both the things as default error action & error method. It uses error view you can also customize this. This is the easy way to customize errors.
To understand more on yii error handling look at this diagram.
Great post! Thx.