Home > Backend Development > PHP Tutorial > How Can I Catch Fatal PHP Errors Using register_shutdown_function?

How Can I Catch Fatal PHP Errors Using register_shutdown_function?

Barbara Streisand
Release: 2024-12-22 19:41:15
Original
314 people have browsed it

How Can I Catch Fatal PHP Errors Using register_shutdown_function?

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"]
        ));
    }
}
Copy after login

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
$errno
File $errfile Line $errline Trace
$trace
HTML; return $content; }
Copy after login

To handle the mailing functionality, define the error_mail function and consider using a library like Swift Mailer.

Additional Resources:

  • [PHP Error Handling](https://www.php.net/manual/en/features.error-handling.php)
  • [$php_errormsg](https://www.php.net/manual/en/reserved.variables.php#constant.$php_errormsg)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template