I am running PHP 5.4.12 on Ubuntu 12.10.
I am using an error handler to turn PHP errors into exceptions so I can handle them. However, I am finding that while I can turn errors into exceptions, there doesn't really seem to be a way to catch the exception at all.
Here's some simple demonstration code:
<?php
class CErrorException extends Exception {}
function handleError($level, $message, $file, $line){
if( error_reporting() != 0){
throw new CErrorException($message, $level);
}
}
function handleException(Exception $exception){
var_dump('Exception handled at global level');
}
set_error_handler('handleError');
set_exception_handler('handleException');
try {
require_once('non\existent\file'); //Will generate an error and cause an exception to be thrown.
} catch (Exception $e) {
var_dump("let's deal with the exception");
}
Unfortunately, in this case, I can never catch the exception that is thrown, which makes it hard to recover from issues caused by using require_once
on a non existent or unreadable file.
I get these 2 errors:
Warning: Uncaught exception 'CErrorException' with message 'require_once(non\existent\file): failed to open stream: Invalid argument' in /work/test.php:7 Stack trace: #0 /work/test.php(20): handleError(2, 'require_once(no...', '/work/test.php', 20, Array) #1 /work/test.php(20): require_once() #2 {main} thrown in /work/test.php on line 7
Fatal error: main(): Failed opening required 'non\existent\file'
Is there simply no way to catch it?
Not all errors are processable with an error handler. A fatal error in PHP core will stop processing of further instructions, which include processing your error handler. From the documentation of set_error_handler():
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.