php5和php7的异常处理机制(thinkphp5 异常处理的分析)-PHP7

资源魔 46 0
本篇文章次要给各人引见php5以及php7的异样解决机制(thinkphp5 异样解决的剖析),心愿对需求的冤家有所协助!

1.php异样以及谬误

正在其余言语中,异样以及谬误是有区分的,然而PHP,碰见本身谬误时,会触发一个谬误,而没有是跑出异样。而且,php年夜局部状况,城市触发谬误,终止顺序执行,正在php5中,try catch是不方法解决谬误的。

php7是能够捕捉谬误的;

1.1 php5 谬误异样

// 1.异样解决
try{
  throw new Exception("Error Processing Request", 1);
}catch ( Exception $e){
  echo $e->getCode().'<br/>';
  echo $e->getMessage().'<br/>';
  echo $e->getLine().'<br/>';
  echo $e->getFile().'<br/>';
}

前往:

1
Error Processing Request
158
E:\phpwebenv\PHPTutorial\WWW\test\index.php

// 2.后果php谬误解决机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>';
echo "Error on line $errline in ".$errfile;
}
set_error_handler('MyErrorHandler',E_ALL|E_STRICT);
try{
// throw new Exception("Error Processing Request", 4);
  trigger_error('error_msg');
}catch ( Exception $e){
  echo $e->getCode().'<br/>';
  echo $e->getMessage().'<br/>';
  echo $e->getLine().'<br/>';
  echo $e->getFile().'<br/>';
}

后果:
Custom error:1024:error_msg
Error on line 164 in E:\phpwebenv\PHPTutorial\WWW\test\index.php

//3. 解决致命谬误:剧本完结后执行
function shutdown_function(){
  $e = error_get_last();
  echo '<pre/>';
  var_dump($e);
}
register_shutdown_function('shutdown_function');
try{
// throw new Exception("Error Processing Request", 4);
// trigger_error('error_msg');
  fun();
}catch ( Exception $e){
  echo $e->getCode().'<br/>';
  echo $e->getMessage().'<br/>';
  echo $e->getLine().'<br/>';
  echo $e->getFile().'<br/>';
}

后果:

Fatal error: Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\
test\index.php:172 Stack trace: #0 {main} thrown in E:\phpwebenv\PHPTutorial\WWW\test\index.php on line 172
array(4) {
  ["type"]=>
  int(1)
  ["message"]=>
  string(131) "Uncaught Error: Call to undefined function fun() in E:\phpwebenv\PHPTutorial\WWW\test\index.php:172
Stack trace:
#0 {main}
  thrown"
  ["file"]=>
  string(43) "E:\phpwebenv\PHPTutorial\WWW\test\index.php"
  ["line"]=>
  int(172)
}
以上办法能够看出,php不捕捉到异样,只能依赖set_error_handler()以及register_shutdown_function();来解决,set_error_handler只能承受
异样以及非致命的谬误。register_shutdown_function():次要针对die()或致命谬误,即顺序终结后执行;以是php5不很好的异样解决机制。

1.2 php7的异样解决

// 解决致命谬误:剧本完结后执行
function shutdown_function(){
    $e = error_get_last();
    echo '<pre>';
    var_dump($e);
}
register_shutdown_function('shutdown_function');
// 后果php谬误解决机制
function MyErrorHandler($error,$errstr,$errfile,$errline){
    echo '<b> Custom error:</b>'.$error.':'.$errstr.'<br/>';
    echo "Error on line $errline in ".$errfile;
}
set_error_handler('MyErrorHandler',E_ALL|E_STRICT);
try{
    // throw new Exception("Error Processing Request", 4);
    // trigger_error('error_msg');
    fun();
}catch ( Error $e){
    echo $e->getCode().'<br/>';
    echo $e->getMessage().'<br/>';
    echo $e->getLine().'<br/>';
    echo $e->getFile().'<br/>';
}
后果:
0
Call to undefined function fun()
172
E:\phpwebenv\PHPTutorial\WWW\test\index.php
NULL  
register_shutdown_function();不捕捉到异样
// 2. 假如不必try catch 捕捉

function exception_handler( Throwable $e){

    echo 'catch Error:'.$e->getCode().':'.$e->getMessage().'<br/>';


}

set_exception_handler('exception_handler');

fun();

总结: Throwable 是Error 以及 Exception 的基类,正在php7中,假如既想捕捉异样有需求捕捉谬误

try{
    fun();
}catch ( Throwable $e){
    echo $e->getCode().'<br/>';
    echo $e->getMessage().'<br/>';
    echo $e->getLine().'<br/>';
    echo $e->getFile().'<br/>';
}

3. thinkphp5框架的谬误解决:

 正在异样谬误解决类:Error有这个解决  
// 注册谬误以及异样解决机制
\think\Error::register();
 /**
     * 注册异样解决
     * @return void
     */
    public static function register()
    {
        error_reporting(E_ALL);
        set_error_handler([__CLASS__, 'appError']);
        set_exception_handler([__CLASS__, 'appException']);
        register_shutdown_function([__CLASS__, 'appShutdown']);
    }
当顺序呈现谬误时,会执行这些异样、谬误的函数;

链接数据库后,解决异样的是:

/**
     * 衔接数据库办法
     * @access public
     * @param array         $config 衔接参数
     * @param integer       $linkNum 衔接序号
     * @param array|bool    $autoConnection 能否主动衔接主数据库(用于散布式)
     * @return PDO
     * @throws Exception
     */
    public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
    {
        if (!isset($this->links[$linkNum])) {
            if (!$config) {
                $config = $this->config;
            } else {
                $config = array_merge($this->config, $config);
            }
            // 衔接参数
            if (isset($config['params']) && is_array($config['params'])) {
                $params = $config['params'] + $this->params;
            } else {
                $params = $this->params;
            }
            // 记载以后字段属性巨细写设置
            $this->attrCase = $params[PDO::ATTR_CASE];

            // 数据前往类型
            if (isset($config['result_type'])) {
                $this->fetchType = $config['result_type'];
            }
            try {
                if (empty($config['dsn'])) {
                    $config['dsn'] = $this->parseDsn($config);
                }
                if ($config['debug']) {
                    $startTime = microtime(true);
                }
                $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);
                if ($config['debug']) {
                    // 记载数据库衔接信息
                    Log::record('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn'], 'sql');
                }
            } catch (\PDOException $e) {
                if ($autoConnection) {
                    Log::record($e->getMessage(), 'error');
                    return $this->connect($autoConnection, $linkNum);
                } else {
                    throw $e;
                }
            }
        }
        return $this->links[$linkNum];
    }

当数据库链接失败后,能够从新链接或许间接抛出异样;

    /**
     * 析构办法
     * @access public
     */
    public function __destruct()
    {
        // 开释查问
        if ($this->PDOStatement) {
            $this->free();
        }
        // 封闭衔接
        $this->close();
    }
当执行sql失败后,挪用析构办法,封闭数据库链接;

4. php发作谬误时,资本开释

php是诠释性剧本,每一个php页面都是一个自力的执行顺序,不论用甚么形式只需执行完了(包罗die(),exit(),致命谬误终止顺序),城市把后果前往给效劳器,城市封闭。顺序都封闭了,资本当然会被开释;

unset();当多个变量名或许工具名指向一块存储地点时,unset()函数的作用仅仅是销毁变量名以及存储地点的指向罢了,当仅有一个变量名或许工具名,unset销毁的是指定的存储地点上的内容;

析构办法:当实例化的工具,不其余变量或工具名指向时,就会执行此办法;或许是正在剧本完结后,开释工具资本时,执行此办法;

相干保举:

《PHP7以及PHP5正在平安上的区分(实例)》

《PHP7 的形象语法树(AST)带来的变动》

《PHP7言语的执行原理(PHP7源码剖析)》

《PHP 7.4估计将正在2019年12月公布》

以上就是php5以及php7的异样解决机制(thinkphp5 异样解决的剖析)的具体内容,更多请存眷资源魔其它相干文章!

标签: PHP5 PHP7 php7开发教程 php7开发资料 php7开发自学 thinkphp5 异常处理机制

抱歉,评论功能暂时关闭!