PHP catches FATAL level errors

Official reference

Official website set_error_handler register_shutdown_function

How to catch all errors perfectly

set_error_handler can be used to capture most error types. When a FATAL level error is encountered, because PHP directly terminates the operation, the callback function set by set_error_handler cannot be triggered. At this time, we need to use register_shutdown_function to set the callback function for program termination. It should be noted that the callback set by register_shutdown_function is executed after the program is terminated, regardless of whether there is an error in the process. So in this callback, we also need to determine whether an error has occurred, and if an error has occurred, we will record it in the log. For details, please refer to the following code.

            set_error_handler('exception_handler');
register_shutdown_function('shutdown_handler');
function exception_handler($err_no, $err_str, $err_file, $err_line)
{
    error_reporting(0);
    // save error log
    // ...
    error_reporting(E_ALL);
}
function shutdown_handler()
{
    $error = error_get_last();
    if (empty($error)) {
        return;
    }
    error_reporting(0);
    // save error log
    // ...
    error_reporting(E_ALL);
}