Handle fatal errors in PHP using register_shutdown_function()

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.

Leave a Comment