1

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?

1 Answer 1

1

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.

2
  • Okay, so how would you recommend handling fatal errors then, if register_shutdown_function() won't handle them? Commented Sep 10, 2013 at 13:54
  • 1
    @ChrisWhite it is not correct to say that it's not 'handle' them. register_shutdown_function() will be executed when script is exiting (and not in all cases - external system process kill is an example when it will not be triggered). So, calling it is a consequence of error, but not a way to handle error. Native fatal errors can not be handled in most cases.
    – Alma Do
    Commented Sep 10, 2013 at 13:59

Not the answer you're looking for? Browse other questions tagged or ask your own question.