0 follower

CErrorHandler

Package system.base
Inheritance class CErrorHandler » CApplicationComponent » CComponent
Implements IApplicationComponent
Since 1.0
Version $Id$
Source Code framework/base/CErrorHandler.php
CErrorHandler handles uncaught PHP errors and exceptions.

It displays these errors using appropriate views based on the nature of the error and the mode the application runs at. It also chooses the most preferred language for displaying the error.

CErrorHandler uses two sets of views:
  • development views, named as exception.php;
  • production views, named as error<StatusCode>.php;
where <StatusCode> stands for the HTTP error code (e.g. error500.php). Localized views are named similarly but located under a subdirectory whose name is the language code (e.g. zh_cn/error500.php).

Development views are displayed when the application is in debug mode (i.e. YII_DEBUG is defined as true). Detailed error information with source code are displayed in these views. Production views are meant to be shown to end-users and are used when the application is in production mode. For security reasons, they only display the error message without any sensitive information.

CErrorHandler looks for the view templates from the following locations in order:
  1. themes/ThemeName/views/system: when a theme is active.
  2. protected/views/system
  3. framework/views
If the view is not found in a directory, it will be looked for in the next directory.

The property maxSourceLines can be changed to specify the number of source code lines to be displayed in development views.

CErrorHandler is a core application component that can be accessed via CApplication::getErrorHandler().

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
adminInfo string the application administrator information (could be a name or email link). CErrorHandler
behaviors array the behaviors that should be attached to this component. CApplicationComponent
discardOutput boolean whether to discard any existing page output before error display. CErrorHandler
error array Returns the details about the error that is currently being handled. CErrorHandler
errorAction string the route (e.g. 'site/error') to the controller action that will be used to display external errors. CErrorHandler
isInitialized boolean whether this application component has been initialized (i.e., init() is invoked. CApplicationComponent
maxSourceLines integer maximum number source code lines to be displayed. CErrorHandler

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
versionInfo string server version information. CErrorHandler

Public Methods

Hide inherited methods

MethodDescriptionDefined By
__call() Calls the named method which is not a class method. CComponent
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
getError() Returns the details about the error that is currently being handled. CErrorHandler
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getIsInitialized() Checks whether this application component has been initialized (i.e., init() is invoked.) CApplicationComponent
handle() Handles the exception/error event. CErrorHandler
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
init() Initializes the application component. CApplicationComponent
raiseEvent() Raises an event. CComponent

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
getExactTrace() Returns the exact trace where the problem occurs CErrorHandler
getSourceLines() Returns the source lines around the error line. CErrorHandler
getVersionInfo() Returns server version information. If the application is in production mode, nothing is returned. CErrorHandler
getViewFile() Determines which view file should be used. CErrorHandler
getViewFileInternal() Looks for the view under the specified directory. CErrorHandler
handleError() Handles the PHP error. CErrorHandler
handleException() Handles the exception. CErrorHandler
render() Renders the view. CErrorHandler

Property Details

adminInfo property
public string $adminInfo;

the application administrator information (could be a name or email link). It is displayed in error pages to end users. Defaults to 'the webmaster'.

discardOutput property
public boolean $discardOutput;

whether to discard any existing page output before error display. Defaults to true.

error property read-only (available since v1.0.6)
public array getError()

Returns the details about the error that is currently being handled. The error is returned in terms of an array, with the following information:

  • 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

errorAction property (available since v1.0.6)
public string $errorAction;

the route (e.g. 'site/error') to the controller action that will be used to display external errors. Inside the action, it can retrieve the error information by Yii::app()->errorHandler->error. This property defaults to null, meaning CErrorHandler will handle the error display.

maxSourceLines property
public integer $maxSourceLines;

maximum number source code lines to be displayed. Defaults to 25.

versionInfo property read-only
protected string getVersionInfo()

server version information. If the application is in production mode, nothing is returned.

Method Details

getError() method (available since v1.0.6)
public array getError()
{return} array the error details. Null if there is no error.
Source Code: framework/base/CErrorHandler.php#114 (show)
public function getError()
{
    return 
$this->_error;
}

Returns the details about the error that is currently being handled. The error is returned in terms of an array, with the following information:

  • 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

getExactTrace() method
protected array getExactTrace(Exception $exception)
$exception Exception the uncaught exception
{return} array the exact trace where the problem occurs
Source Code: framework/base/CErrorHandler.php#211 (show)
protected function getExactTrace($exception)
{
    
$traces=$exception->getTrace();
    
$result=null;
    foreach(
$traces as $trace)
    {
        
// property access exception
        
if(isset($trace['function']) && ($trace['function']==='__get' || $trace['function']==='__set'))
            return 
$trace;
    }
    return 
null;
}

getSourceLines() method
protected array getSourceLines(string $file, integer $line)
$file string source file path
$line integer the error line number
{return} array source lines around the error line, indxed by line numbers
Source Code: framework/base/CErrorHandler.php#314 (show)
protected function getSourceLines($file,$line)
{
    
// determine the max number of lines to display
    
$maxLines=$this->maxSourceLines;
    if(
$maxLines<1)
        
$maxLines=1;
    else if(
$maxLines>100)
        
$maxLines=100;

    
$line--;    // adjust line number to 0-based from 1-based
    
if($line<|| ($lines=@file($file))===false || ($lineCount=count($lines))<=$line)
        return array();

    
$halfLines=(int)($maxLines/2);
    
$beginLine=$line-$halfLines>0?$line-$halfLines:0;
    
$endLine=$line+$halfLines<$lineCount?$line+$halfLines:$lineCount-1;

    
$sourceLines=array();
    for(
$i=$beginLine;$i<=$endLine;++$i)
        
$sourceLines[$i+1]=$lines[$i];
    return 
$sourceLines;
}

Returns the source lines around the error line. At most maxSourceLines lines will be returned.

getVersionInfo() method
protected string getVersionInfo()
{return} string server version information. If the application is in production mode, nothing is returned.
Source Code: framework/base/CErrorHandler.php#294 (show)
protected function getVersionInfo()
{
    if(
YII_DEBUG)
    {
        
$version='<a href="https://www.yiiframework.com/">Yii Framework</a>/'.Yii::getVersion();
        if(isset(
$_SERVER['SERVER_SOFTWARE']))
            
$version=$_SERVER['SERVER_SOFTWARE'].' '.$version;
    }
    else
        
$version='';
    return 
$version;
}

getViewFile() method
protected string getViewFile(string $view, integer $code)
$view string view name (either 'exception' or 'error')
$code integer HTTP status code
{return} string view file path
Source Code: framework/base/CErrorHandler.php#250 (show)
protected function getViewFile($view,$code)
{
    
$viewPaths=array(
        
Yii::app()->getTheme()===null null :  Yii::app()->getTheme()->getSystemViewPath(),
        
Yii::app() instanceof CWebApplication Yii::app()->getSystemViewPath() : null,
        
YII_PATH.DIRECTORY_SEPARATOR.'views',
    );

    foreach(
$viewPaths as $i=>$viewPath)
    {
        if(
$viewPath!==null)
        {
             
$viewFile=$this->getViewFileInternal($viewPath,$view,$code,$i===2?'en_us':null);
             if(
is_file($viewFile))
                  return 
$viewFile;
        }
    }
}

Determines which view file should be used.

getViewFileInternal() method
protected string getViewFileInternal(string $viewPath, string $view, integer $code, string $srcLanguage=NULL)
$viewPath string the directory containing the views
$view string view name (either 'exception' or 'error')
$code integer HTTP status code
$srcLanguage string the language that the view file is in
{return} string view file path
Source Code: framework/base/CErrorHandler.php#277 (show)
protected function getViewFileInternal($viewPath,$view,$code,$srcLanguage=null)
{
    
$app=Yii::app();
    if(
$view==='error')
    {
        
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."error{$code}.php",$srcLanguage);
        if(!
is_file($viewFile))
            
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR.'error.php',$srcLanguage);
    }
    else
        
$viewFile=$app->findLocalizedFile($viewPath.DIRECTORY_SEPARATOR."exception.php",$srcLanguage);
    return 
$viewFile;
}

Looks for the view under the specified directory.

handle() method
public void handle(CEvent $event)
$event CEvent the event containing the exception/error information
Source Code: framework/base/CErrorHandler.php#83 (show)
public function handle($event)
{
    
// set event as handled to prevent it from being handled by other event handlers
    
$event->handled=true;

    if(
$this->discardOutput)
    {
        while(@
ob_end_clean()) ;
    }

    if(
$event instanceof CExceptionEvent)
        
$this->handleException($event->exception);
    else 
// CErrorEvent
        
$this->handleError($event);
}

Handles the exception/error event. This method is invoked by the application whenever it captures an exception or PHP error.

handleError() method
protected void handleError(CErrorEvent $event)
$event CErrorEvent the PHP error event
Source Code: framework/base/CErrorHandler.php#163 (show)
protected function handleError($event)
{
    
$trace=debug_backtrace();
    
// skip the first 3 stacks as they do not tell the error position
    
if(count($trace)>3)
        
$trace=array_slice($trace,3);
    
$traceString='';
    foreach(
$trace as $i=>$t)
    {
        if(!isset(
$t['file']))
            
$t['file']='unknown';
        if(!isset(
$t['line']))
            
$t['line']=0;
        if(!isset(
$t['function']))
            
$t['function']='unknown';
        
$traceString.="#$i {$t['file']}({$t['line']}): ";
        if(isset(
$t['object']) && is_object($t['object']))
            
$traceString.=get_class($t['object']).'->';
        
$traceString.="{$t['function']}()\n";
    }

    
$app=Yii::app();
    if(
$app instanceof CWebApplication)
    {
        
$this->_error=$data=array(
            
'code'=>500,
            
'type'=>'PHP Error',
            
'message'=>$event->message,
            
'file'=>$event->file,
            
'line'=>$event->line,
            
'trace'=>$traceString,
            
'source'=>$this->getSourceLines($event->file,$event->line),
        );
        if(!
headers_sent())
            
header("HTTP/1.0 500 PHP Error");
        if(
YII_DEBUG)
            
$this->render('exception',$data);
        else
            
$this->render('error',$data);
    }
    else
        
$app->displayError($event->code,$event->message,$event->file,$event->line);
}

Handles the PHP error.

handleException() method
protected void handleException(Exception $exception)
$exception Exception the exception captured
Source Code: framework/base/CErrorHandler.php#123 (show)
protected function handleException($exception)
{
    
$app=Yii::app();
    if(
$app instanceof CWebApplication)
    {
        if((
$trace=$this->getExactTrace($exception))===null)
        {
            
$fileName=$exception->getFile();
            
$errorLine=$exception->getLine();
        }
        else
        {
            
$fileName=$trace['file'];
            
$errorLine=$trace['line'];
        }
        
$this->_error=$data=array(
            
'code'=>($exception instanceof CHttpException)?$exception->statusCode:500,
            
'type'=>get_class($exception),
            
'message'=>$exception->getMessage(),
            
'file'=>$fileName,
            
'line'=>$errorLine,
            
'trace'=>$exception->getTraceAsString(),
            
'source'=>$this->getSourceLines($fileName,$errorLine),
        );

        if(!
headers_sent())
            
header("HTTP/1.0 {$data['code']} ".get_class($exception));
        if(
$exception instanceof CHttpException || !YII_DEBUG)
            
$this->render('error',$data);
        else
            
$this->render('exception',$data);
    }
    else
        
$app->displayException($exception);
}

Handles the exception.

render() method
protected void render(string $view, array $data)
$view string the view name (file name without extension). See getViewFile for how a view file is located given its name.
$data array data to be passed to the view
Source Code: framework/base/CErrorHandler.php#230 (show)
protected function render($view,$data)
{
    if(
$view==='error' && $this->errorAction!==null)
        
Yii::app()->runController($this->errorAction);
    else
    {
        
// additional information to be passed to view
        
$data['version']=$this->getVersionInfo();
        
$data['time']=time();
        
$data['admin']=$this->adminInfo;
        include(
$this->getViewFile($view,$data['code']));
    }
}

Renders the view.