Home  >  Q&A  >  body text

How to catch PHP fatal errors (`E_ERROR`)?

<p>I can use <code>set_error_handler()</code> to catch most PHP errors, but it does not work for fatal (<code>E_ERROR</code>) errors, such as calling a non-existent function. Is there any other way to catch these errors? </p> <p>I'm trying to resolve all errors by calling <code>mail()</code> and am running PHP 5.2.3. </p>
P粉978551081P粉978551081440 days ago554

reply all(1)I'll reply

  • P粉576184933

    P粉5761849332023-08-28 11:12:14

    Use register_shutdown_function to log fatal errors, this 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 must 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 = "
        ";
    return $content;
    }
    

    Use Swift Mailer to write the error_mail function.

    See also:

    reply
    0
  • Cancelreply
  • ItemDescription
    Error
    $errstr
    Error number
    $errno
    document $Error file
    OK $Error line
    track
    $trace