How do I catch a PHP fatal (`E_ERROR`) error?

前端 未结 17 2566
北荒
北荒 2020-11-21 06:21

I can use set_error_handler() to catch most PHP errors, but it doesn\'t work for fatal (E_ERROR) errors, such as calling a function that doesn\'t e

17条回答
  •  轮回少年
    2020-11-21 06:55

    You can't catch/handle fatal errors, but you can log/report them. For quick debugging I modified one answer to this simple code

    function __fatalHandler()
    {
        $error = error_get_last();
    
        // Check if it's a core/fatal error, otherwise it's a normal shutdown
        if ($error !== NULL && in_array($error['type'],
            array(E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
                  E_COMPILE_ERROR, E_COMPILE_WARNING,E_RECOVERABLE_ERROR))) {
    
            echo "
    fatal error:\n";
            print_r($error);
            echo "
    "; die; } } register_shutdown_function('__fatalHandler');

提交回复
热议问题