Search code examples
phperror-handlingfatal-errorparse-error

Managing PHP Errors


I have been searching all over the net to try and find a way to catch all errors thrown by PHP (5.3)

I have been reading through the documentation and it looks like set_error_handler is what I need but it doesn't get fatal/parse errors. I'm not sure if this is possible...

Here is my source: https://github.com/tarnfeld/PHP-Error-Handler Feel free to fork/commit if you know better solutions to all of this.

Thanks in advanced!

Updated!

Using the answers below I finished writing an error handler, it takes care of E_ERROR|E_PARSE|E_WARNING|E_NOTICE and will kill the script when it is fatal! :-)


Solution

  • Quoting the manual:

    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.

    This means Fatals cannot be caught and handled. What you can do is setup an additional handler to be run when the script exits, e.g. register_shutdown_function.

    In that handler, use error_get_last and check if it was a Fatal Error. This will not allow you to continue script execution though. The script will end, but you can do any cleanup or logging (usually fatals will be logged anyway to the error.log) or whatever.

    There is a user-supplied example in the comments below set_error_handler

    register_shutdown_function('shutdownFunction');
    function shutDownFunction() {
        $error = error_get_last();
        if ($error['type'] == 1) {
            //do your stuff    
        }
    }
    

    But note that this still will only catch certain additional runtime errors.