Handle fatal errors in PHP using register_shutdown_function()

后端 未结 4 1530
南旧
南旧 2020-11-27 14:49

According to the comment on this answer it is possible to catch Fatal Errors through a shutdown function which cannot be caught using set_error_handler().

4条回答
  •  旧时难觅i
    2020-11-27 15:00

    This works for me:

    function shutdown() {
        $error = error_get_last();
        if ($error['type'] === E_ERROR) {
            // fatal error has occured
        }
    }
    
    register_shutdown_function('shutdown');
    
    spl_autoload_register('foo'); 
    // throws a LogicException which is not caught, so triggers a E_ERROR
    

    However, you probably know it already, but just to make sure: you can't recover from a E_ERROR in any way.

    As for the backtrace, you can't... :( In most cases of a fatal error, especially Undefined function errors, you don't really need it. Pinpointing the file/line where it occured is enough. The backtrace is irrelevant in that case.

提交回复
热议问题