zoukankan      html  css  js  c++  java
  • PHP捕获Fatal error错误与异常处理

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

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

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

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

    <?php
     
    error_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() 来捕获错误

    <?php
     
    error_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{}能够捕获到。

    <?php
     
    error_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中无法捕获到的错误。

    <?php
     
    error_reporting(E_ALL);
    ini_set('display_errors', 'on');
     
    try {
        hello();
    } catch (Throwable $e) {
        echo $e->getMessage();
    }
  • 相关阅读:
    python高阶函数——返回函数(闭包)
    python高阶函数——sorted排序算法
    python高阶函数—filter
    python高阶函数——map/reduce
    Python——高阶函数概念(Higher-order function)
    Python高级特性——迭代器
    Python高级特性——生成器(generator)
    Python高级特性——列表生成式(list Comprehensions)
    Python高级特性——迭代(Iteration)
    Python高级特性——切片(Slice)
  • 原文地址:https://www.cnblogs.com/xi-jie/p/12976745.html
Copyright © 2011-2022 走看看