Catching PHP Fatal Errors Through Registering a Shutdown Function
Problem:
While set_error_handler() can handle most PHP errors, it fails to capture fatal errors (E_ERROR), such as those caused by calling nonexistent functions.
Solution:
PHP 5.2 introduces the register_shutdown_function, which allows you to log fatal errors:
register_shutdown_function("fatal_handler"); function fatal_handler() { // Capture error information $error = error_get_last(); if ($error) { error_mail(format_error( $error["type"], $error["message"], $error["file"], $error["line"] )); } }
Define the format_error function to format the error information:
function format_error($errno, $errstr, $errfile, $errline) { // Generate the error trace $trace = print_r(debug_backtrace(false), true); // Format the error information $content = <<<HTML <table border="1"> <thead> <th>Item</th> <th>Description</th> <thead> <tbody> <tr> <td>Error</td> <td><pre class="brush:php;toolbar:false">$errstr
$errno
$trace
To handle the mailing functionality, define the error_mail function and consider using a library like Swift Mailer.
Additional Resources:
The above is the detailed content of How Can I Catch Fatal PHP Errors Using register_shutdown_function?. For more information, please follow other related articles on the PHP Chinese website!