John Dorean
John Dorean

Reputation: 3874

Catching fatal PHP errors and throwing an exception

The entry point (front controller) for our software is wrapped in a try catch block which catches exceptions and then includes a PHP file to show a friendly error page, as well as emailing us about the exception. This work perfectly, however it misses PHP fatal errors which just show a HTTP 500 response. I'm trying to catch those errors in the same way as exceptions.

At the moment, we have this in the application's entry point:

try {
    // Register a shutdown handler for fatal errors
    register_shutdown_function(function() {
        $error = error_get_last();

        // Did this request throw an error that wasn't handled?
        if ($error !== null) {
            throw new Exception('PHP fatal error!');
        }
    });

    // ...normal front controller stuff
} catch (Exception $e) {
    // show fancy error screen with debug information
    include 'themes/error/500.php';
}

Here, I'm throwing an exception when PHP throws a fatal error in the hopes that it gets handled by the normal exception handling procedure. However, the exception never gets caught:

Fatal error: Uncaught exception 'Exception' with message 'PHP fatal error!'

How can I achieve what I want to do here?

Upvotes: 1

Views: 3230

Answers (1)

Alma Do
Alma Do

Reputation: 37365

You should not use register_shutdown_function() for that - it makes no sense since you're already at stage when script is exiting. PHP allow you to handle errors via set_error_handler() function.

But note, you can not handle fatal errors with that (such as calling undefined functions) - and, of cause, parse error as well:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

Upvotes: 1

Related Questions