in the process of finding YII2 related development data, it was found that many people were unclear about yii2 's error-handling process, and in particular, there were often some doubts, such as " Why does my program automatically print out errors when problems occur? How does it listen? Where do you use the try Catch? , I would like to describe in detail the error handling process , which I hope will help you learn about the Yii framework .
Predefined open error Handling constants
# \yii\baseyii.php/**
* This constant defines whether error handling should is enabled. Defaults to True.
*/
Defined (\ ' yii_enable_error_handler\ ') or define (\ ' Yii_enable_error_handler\ ', true);
pre-defined default components ErrorHandler
yii2\web\application.php
/**
* @inheritdoc
* /public function corecomponents() {
return array_merge (parent:: Corecomponents (), [
\ ' request\ ' = [\ ' class\ ' = ' yii\web\request\ '],
\ ' response\ ' = [\ ' class\ ' = ' yii\web\response\ '],
\ ' session\ ' = [\ ' class\ ' = ' yii\web\session\ '],
\ ' user\ ' = [\ ' class\ ' = ' yii\web\user\ '],
\ ' errorhandler\ ' = [\ ' class\ ' = ' yii\web\errorhandler\ '],
]);
}
run-time initialization registration error handling mechanism Registererrorhandler
yii\base\application.php
Public function __construct ($config = []) {
Yii:: $app = $this;
$this->setinstance ($this);
$this->state = self:: state_begin;
$this->preinit ($config);
$this->registererrorhandler ($config);
Component::__construct ($config);
}#/**
* registering error handling components
* @param array $config application config
*/protected function registererrorhandler(& $config) {
if (Yii_enable_error_handler) {
if (! isset ($config [\ ' components\ '][\ ' errorhandler\ '][\ ' class\ '])) {
Echo "Error:no ErrorHandler component is configured.\n";
Exit (1);
}
$this->set (\ ' Errorhandler\ ', $config [\ ' components\ '][\ ' errorhandler\ ']);
unset ($config [\ ' components\ '][\ ' errorhandler\ ']);
$this->geterrorhandler ()->register ();
}
}
analysis of yii\web\errorhandler processing class Register Method
/**
* Register This error handler
* /public function Register() {
Ini_set (\ ' Display_errors\ ', false);
Set_exception_handler ([$this, \ ' handleexception\ ']);
Set_error_handler ([$this, \ ' handleerror\ ']);
if ($this->memoryreservesize > 0) {
$this->_memoryreserve = str_repeat (\ ' x\ ', $this->memoryreservesize);
}
Register_shutdown_function ([$this, \ ' handlefatalerror\ ']);
}
From the above method, we can see thatyii2 through the global exception handling function set_exception_handler Set the method of handling exceptions, through all error handling functions Set_error_handler Sets the method for handling errors. When there is an exception or error setting in the code, if there is no further exception handling mechanism in the upper layer, it will be captured and processed by the whole global function .
Source: Dust
Error handling for YII2 framework