views:

677

answers:

4

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

+4  A: 

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()

Cassy
+3  A: 

You can track these errors (except for E_PARSE) like this:

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');
Deniss Kozlovs
Have you tested it?
Peter Lindqvist
A: 

The script with parse error is always interrupted and it can not be handled. So if the script is called directly or by include/require, there is nothing you can do. But if it is called by AJAX, flash or any other way, there is a workaround how to detect parse errors.

I needed this to handle swfupload script. Swfupload is a flash that handles file uploads and everytime file is uploaded, it calls PHP handling script to handle filedata - but there is no browser output, so the PHP handling script needs these settings for debugging purposes:

  • warnings and notices ob_start(); at the beginning and store content into session by ob_get_contents(); at the end of the handling script: This can be displayed into browser by another script
  • fatal errors register_shutdown_function() to set the session with the same trick as above
  • parse errors if the ob_get_contents() is located at the end of the handling script and parse error occured before, the session is not filled (it is null). The debugging script can handle it this way: if(!isset($_SESSION["swfupload"])) echo "parse error";

Note 1 null means is not set to isset()

Jan Turoň
+3  A: 

You should use Lagger library

StanlyQ