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

前端 未结 17 2560
北荒
北荒 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:47

    Log fatal errors using the register_shutdown_function, which requires PHP 5.2+:

    register_shutdown_function( "fatal_handler" );
    
    function fatal_handler() {
        $errfile = "unknown file";
        $errstr  = "shutdown";
        $errno   = E_CORE_ERROR;
        $errline = 0;
    
        $error = error_get_last();
    
        if($error !== NULL) {
            $errno   = $error["type"];
            $errfile = $error["file"];
            $errline = $error["line"];
            $errstr  = $error["message"];
    
            error_mail(format_error( $errno, $errstr, $errfile, $errline));
        }
    }
    

    You will have to define the error_mail and format_error functions. For example:

    function format_error( $errno, $errstr, $errfile, $errline ) {
        $trace = print_r( debug_backtrace( false ), true );
    
        $content = "
        
    ItemDescription
    Error
    $errstr
    Errno
    $errno
    File $errfile
    Line $errline
    Trace
    $trace
    "; return $content; }

    Use Swift Mailer to write the error_mail function.

    See also:

    • $php_errormsg
    • Predefined Constants

提交回复
热议问题