I’m trying to update an older application to make use of newer PHP 8.2+ features. Many internal PHP errors are now automatically thrown as ErrorException
objects.
You can set up a custom function to handle any ErrorException
objects that are thrown but not caught.
The issue is that sometimes, however, PHP seems to be throwing both an ErrorException
object and also using the old error handler at the same time. This results in the same error being processed twice.
Please consider the following simplified code:
// Setup Error Handling
ErrorHandler::Init();
// Try to include a file that doesn't exist:
require '/path/to/nothing.php';
// The simple error class:
abstract class ErrorHandler {
static public function Init(){
set_exception_handler('ErrorHandler::FinalException');
set_error_handler('ErrorHandler::BasicErrorHandler');
}
static public function FinalException($e){
echo '<br>FinalException() TRIGGERED!<br>';
}
static public function BasicErrorHandler($errorNo){
echo '<br>ErrorHandler() TRIGGERED!<br>';
}
}
When the missing file error occurs, the output is:
ErrorHandler() TRIGGERED!
FinalException() TRIGGERED!
That is, both the exception handler and the error handler are running for the same error.
If possible, I’d rather just use exceptions. But if I don’t use set_error_handler()
, I still get a standard error message in addition to the exception. It just doesn’t get passed to a handler.
-
Is it possible to set a flag that turns off all of the old style error handling and uses only exceptions, so that I don’t need to set
set_error_handler()
in addition toset_exception_handler()
? -
If not, how can I detect inside my custom error handler (which always runs first) if the same error will also be thrown by PHP as an
ErrorException
so it doesn’t get handled twice?