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

前端 未结 17 2578
北荒
北荒 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

    I developed this function to make it possible to "sandbox" code that could cause a fatal error. Since exceptions thrown from the closure register_shutdown_function don't get emitted from the pre-fatal error call stack, I'm forced to exit after this function to provide a uniform way of using it.

    function superTryCatchFinallyAndExit( Closure $try, Closure $catch = NULL, Closure $finally )
    {
        $finished = FALSE;
        register_shutdown_function( function() use ( &$finished, $catch, $finally ) {
            if( ! $finished ) {
                $finished = TRUE;
                print "EXPLODE!".PHP_EOL;
                if( $catch ) {
                    superTryCatchFinallyAndExit( function() use ( $catch ) {
                        $catch( new Exception( "Fatal Error!!!" ) );
                    }, NULL, $finally );                
                } else {
                    $finally();                
                }
            }
        } );
        try {
            $try();
        } catch( Exception $e ) {
            if( $catch ) {
                try {
                    $catch( $e );
                } catch( Exception $e ) {}
            }
        }
        $finished = TRUE;
        $finally();
        exit();
    }
    

提交回复
热议问题