码迷,mamicode.com
首页 > Web开发 > 详细

yii2框架的错误处理

时间:2016-12-21 15:48:46      阅读:570      评论:0      收藏:0      [点我收藏+]

标签:

在查找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框架的错误处理

标签:

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
jiangjie190
加入时间:2016-02-19
  关注此人  发短消息
文章分类
jiangjie190”关注的人------(0
jiangjie190”的粉丝们------(0
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!