PHP7以上的异常处理变化

2021年7月19日10:37:39


https://www.php.net/manual/zh/class.throwable

PHP 7 里,Throwable 是能被 throw 语句抛出的最基本的接口(interface),包含了 Error 和 Exception。

 

注意这里error和exception都是实现Throwable 接口,所以在要捕获error和exception,就可以直接捕获Throwable 

demo

try {

    throw new \Error('error');
    throw new \Exception('exception');

} catch (\Throwable $t) {
    p($t);
}
如果需要自定义异常错误全局捕捉

set_error_handler('zx_error');
set_exception_handler('zx_exception');
ini_set("display_errors", "off");
error_reporting(E_ALL);

function zx_error($errno, $errstr, $errfile, $errline)
{
    p($errno);
    p($errstr);
    p($errfile);
    p($errline);
}

function zx_exception($exception)
{
    p($exception);
}

需要注意的地方,在PHP7以下的是不能在逻辑代码里捕捉error的,只能在set_error_handler里面全局捕捉

所以如果你的 项目可以上PHP7的建议就上,值得主要的点有两个,1,PHP7以上的性能比php7一下的增长30%以上,2,虽然PHP不是一个注重语法糖的语言,但是一些便利性的语法糖,在php以上有很多改变

2022年7月26日13:34:24

新增一些测试代码

function p($data = null)
{
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}

function errorHandler($errno, $errstr, $errfile, $errline)
{
    p('ErrorHandler');
    p($errno);
    p($errstr);
    p($errfile);
    p($errline);
}

function exceptionHandler(Throwable $e)
{
    p('exceptionHandler');
    p($e->getMessage());
}

function shutdown()
{
    p('shutdown');
}

$old_error_handler = set_error_handler("errorHandler");
$old_error_handler = set_exception_handler("exceptionHandler");
register_shutdown_function('shutdown');

//trigger_error('cesssss ');

//throw new Exception('22222');

$r = 4 / 0; //这里触发的是一个异常

file_get_contents('1.log'); //这里触发的是是一个io错误

posted on 2021-07-19 10:47  zh7314  阅读(74)  评论(0编辑  收藏  举报