PHP : Custom error handler - handling parse & fatal errors

Viewed 56731

How can i handle parse & fatal errors using a custom error handler?

6 Answers

Simple Answer: You can't. See 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.

For every other error, you can use set_error_handler()

EDIT:

Since it seems, that there are some discussions on this topic, with regards to using register_shutdown_function, we should take a look at the definition of handling: To me, handling an error means catching the error and reacting in a way that is "nice" for the user and the underlying data (databases, files, web services, etc.).

Using register_shutdown_function you cannot handle an error from within the code where it was called, meaning the code would still stop working at the point where the error occurs. You can, however, present the user with an error message instead of a white page, but you cannot, for example, roll back anything that your code did prior to failing.

You can track these errors using code like this:

(Parse errors can only be caught if they occur in other script files via include() or require(), or by putting this code into an auto_prepend_file as other answers have mentioned.)

function shutdown() {
    $isError = false;

    if ($error = error_get_last()){
    switch($error['type']){
        case E_ERROR:
        case E_CORE_ERROR:
        case E_COMPILE_ERROR:
        case E_USER_ERROR:
            $isError = true;
            break;
        }
    }

    if ($isError){
        var_dump ($error);//do whatever you need with it
    }
}

register_shutdown_function('shutdown');
Related