Home > Backend Development > PHP Tutorial > How Can I Catch and Handle Fatal PHP Errors (E_ERROR) Using `register_shutdown_function()`?

How Can I Catch and Handle Fatal PHP Errors (E_ERROR) Using `register_shutdown_function()`?

DDD
Release: 2024-12-29 08:02:17
Original
174 people have browsed it

How Can I Catch and Handle Fatal PHP Errors (E_ERROR) Using `register_shutdown_function()`?

Catching Fatal (E_ERROR) PHP Errors

Problem:

Although the set_error_handler() function is effective for capturing most PHP errors, it fails to handle fatal errors, such as calling nonexistent functions. This leaves developers seeking alternative methods for capturing these critical errors.

Solution:

PHP 5.2 provides the register_shutdown_function() function that enables capturing of fatal errors. Here's an implementation to send error emails upon encountering such errors:

register_shutdown_function("fatal_handler");

function fatal_handler() {
    $error = error_get_last();  // Obtain last error

    if ($error !== NULL) {
        $errno = $error["type"];
        $errfile = $error["file"];
        $errline = $error["line"];
        $errstr = $error["message"];

        error_mail(format_error($errno, $errstr, $errfile, $errline));
    }
}
Copy after login

Supporting Functions:

Define the necessary supporting functions, such as format_error and error_mail. The format_error function can return the error information in a table format:

function format_error($errno, $errstr, $errfile, $errline) {
    $trace = print_r(debug_backtrace(false), true);
    $content = <<<HTML
    <table>
        <thead><th>Item</th><th>Description</th></thead>
        <tbody>
            <tr><th>Error</th><td><pre class="brush:php;toolbar:false">$errstr
Errno
$errno
File$errfile Line$errline Trace
$trace
HTML; return $content; }
Copy after login

Utilize Swift Mailer library to implement the error_mail function.

Additional Resources:

  • [$php_errormsg](https://www.php.net/manual/en/reserved.variables.errormsg.php)
  • [Predefined Constants](https://www.php.net/manual/en/language.constants.predefined.php)

The above is the detailed content of How Can I Catch and Handle Fatal PHP Errors (E_ERROR) 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template