php捕获Fatal error错误与异常处理

php中的错误和异常是两个不同的概念。

错误:是因为脚本的问题,比如少写了分号,调用未定义的函数,除0,等一些编译语法错误。

异常:是因为业务逻辑和流程,不符合预期情况,比如验证请求参数,不通过就用 throw new 抛一个异常。

在php5的版本中,错误是无法被 try {} catch 捕获的,如下所示:

<?phperror_reporting(E_ALL);ini_set(‘display_errors‘, ‘on‘);try { hello();} catch (\Exception $e) { echo $e->getMessage();}

运行脚本,最终php报出一个Fatal error,并程序中止。

Fatal error: Uncaught Error: Call to undefined function hello() 

有些时候,我们需要捕获这种错误,并做相应的处理。

那就需要用到 register_shutdown_function() 和 error_get_last() 来捕获错误

<?phperror_reporting(E_ALL);ini_set(‘display_errors‘, ‘on‘);//注册一个会在php中止时执行的函数register_shutdown_function(function () { //获取最后发生的错误 $error = error_get_last(); if (!empty($error)) { echo $error[‘message‘], ‘<br>‘; echo $error[‘file‘], ‘ ‘, $error[‘line‘]; }});hello();

我们还可以通过 set_error_handler() 把一些Deprecated、Notice、Waning等错误包装成异常,让 try {} catch 能够捕获到。

<?phperror_reporting(E_ALL);ini_set(‘display_errors‘, ‘on‘);//捕获Deprecated、Notice、Waning级别错误set_error_handler(function ($errno, $errstr, $errfile) { throw new \Exception($errno . ‘ : ‘ . $errstr . ‘ : ‘ . $errfile); //返回true,表示错误处理不会继续调用 return true;});try { $data = []; echo $data[‘index‘];} catch (\Exception $e) { //捕获Notice: Undefined index echo $e->getMessage();}

对于php7中的错误捕获,因为php7中定义了 Throwable 接口,大部分的 Error 和 Exception 实现了该接口。

所以我们在php7中,可以通过 try {} catch(\Throwable $e) 来捕获php5中无法捕获到的错误。

<?phperror_reporting(E_ALL);ini_set(‘display_errors‘, ‘on‘);try { hello();} catch (\Throwable $e) { echo $e->getMessage();} 

  

相关文章