I'm trying to catch as many errors as possible in PHP and properly handle them in a non-default way. My question is best illustrated in this example:
<?php
function errorHandler($errno, $errstr, $errfile, $errline){
echo "Error handler here <br>\n";
//throw new Exception($errstr);
}
fu开发者_如何学运维nction shutdownFunction() {
echo "Hi I'm in here <br>\n";
}
set_error_handler("errorHandler");
register_shutdown_function("shutdownFunction");
try {
$undefined->ok(); // causes some error
} catch(Exception $e) {
echo "Caught the exception <br>\n";
}
The result of running this code as a PHP program will indicate that errorHandler()
is run, a PHP error is printed (if "display_errors" is set to "On"), and then shutdownFunction()
is run.
The problem I'm having arises if I uncomment out that exception throw; I want to throw exceptions on PHP errors as often as possible. If I uncomment the throw
statement out, then the error handler is called, which throws an exception thus causing a further error which results in shutdownFunction()
not to be called.
It is my understanding that I can't make this error into a catchable exception; however, I would at least like to ensure that the shutdown function is called without restricting my ability to catch at least some php errors as exceptions (meaning I don't want to remove that throw
statement in errorHandler()
).
Is there some check in the errorHandler that I can do to check whether or not throwing it will cause shutdownFunction()
to be bypassed?
Throw an exception from the error handler, then use set_exception_handler to handle uncaught exceptions.
So the way I'm solving this is to check if the $errstr parameter starts with "Undefined variable" - and if it does, then I'm not throwing the exception. I suppose if there are any other errors that have a similar issue, i'll do the same thing with those. I can't find a comprehensive list of php errors and what their affects are though, so it'll have to be ad hoc
精彩评论