PHP Trick: Catching fatal errors (E_ERROR) with a custom error handler
Implementing a custom error handler using set_error_handler() in PHP can be a useful technique (Google search for more info/examples)
Unfortunately, set_error_handler() doesn’t catch fatal errors - as the PHP docs say:
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.
Handily, I just discovered it’s possible to catch fatal E_ERROR errors and direct them to your custom error handler using a combination of register_shutdown_function() and error_get_last():
set_error_handler('myErrorHandler');
register_shutdown_function('fatalErrorShutdownHandler');
function myErrorHandler($code, $message, $file, $line) {
...
}
function fatalErrorShutdownHandler()
{
$last_error = error_get_last();
if ($last_error['type'] === E_ERROR) {
// fatal error
myErrorHandler(E_ERROR, $last_error['message'], $last_error['file'], $last_error['line']);
}
}
The key is that functions registered with register_shutdown_function() are called even on a fatal error - including out of memory errors. error_get_last() can then be used to detect whether we’re ending the script because of a fatal error, and pass the error info to your custom error handler if so.
