yii2架構的錯誤處理

來源:互聯網
上載者:User

標籤:

在尋找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架構的錯誤處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.