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();
    } 
    

      

  • 相关阅读:
    flink 读取kafka 数据,partition分配
    Flink 报错 "Could not find a suitable table factory for 'org.apache.flink.table.factories.StreamTableSourceFactory' in the classpath"
    flume接收http请求,并将数据写到kafka
    【翻译】Flume 1.8.0 User Guide(用户指南) Processors
    【翻译】Flume 1.8.0 User Guide(用户指南) Channel
    【翻译】Flume 1.8.0 User Guide(用户指南) Sink
    【翻译】Flume 1.8.0 User Guide(用户指南) source
    【翻译】Flume 1.8.0 User Guide(用户指南)
    Apache Flink 简单安装
    Java之使用IDE
  • 原文地址:https://www.cnblogs.com/jkko123/p/10840358.html
Copyright © 2011-2022 走看看