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 exist. Is there another way to catch these errors?
I am trying to call mail()
for all errors and am running PHP 5.2.3.
Fatal Error Fatal errors are ones that crash your program and are classified as critical errors. An undefined function or class in the script is the main reason for this type of error.
It's an error that caused the script to abort and exit immediately. All statements after the fatal error are never executed. I strongly recommend you use an editor that will alert you to errors as you code. It will safe you a lot of time.
What is E_ERROR? PHP's E_ERROR typically indicates a major issue with PHP. Normally, PHP may be able to recover from a lesser error and the PHP application could continue to run. However, with E_ERROR , PHP will usually outright fail and stop working entirely.
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 = " <table> <thead><th>Item</th><th>Description</th></thead> <tbody> <tr> <th>Error</th> <td><pre>$errstr</pre></td> </tr> <tr> <th>Errno</th> <td><pre>$errno</pre></td> </tr> <tr> <th>File</th> <td>$errfile</td> </tr> <tr> <th>Line</th> <td>$errline</td> </tr> <tr> <th>Trace</th> <td><pre>$trace</pre></td> </tr> </tbody> </table>"; return $content; }
Use Swift Mailer to write the error_mail
function.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With