標籤:
在尋找yii2相關開發資料過程中發現很多人對yii2的錯誤處理流程不清楚,尤其是經常有一些疑惑,比如”為什麼我的程式一旦出現問題,就會自動列印出錯誤呢?它是怎麼監聽的?在哪裡用的try catch?”,下面我詳細的描述一下錯誤處理流程,希望對大家學習yii架構有所協助。
預定義開啟錯誤處理常量
# \yii\BaseYii.php/**
* This constant defines whether error handling should be enabled. Defaults to true.
*/
defined(\’YII_ENABLE_ERROR_HANDLER\’) or define(\’YII_ENABLE_ERROR_HANDLER\’, true);
預定義預設組件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\’],
]);
}
運行時初始化註冊錯誤處理機制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);
}#/**
* 註冊錯誤處理組件
* @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();
}
}
分析yii\web\ErrorHandler處理類register方法
/**
* 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\’]);
}
通過上面的方法,我們能看到,yii2通過全域異常處理函數set_exception_handler設定處理異常的方法,通過全部錯誤處理函數set_error_handler設定了處理錯誤的方法。當有代碼中有異常或者錯誤設定的時候,如果上層沒有進一步的異常處理機制,就會被整個全域函數捕捉,並加以處理。
來源:塵埃
yii2架構的錯誤處理