Is it possible to have PHP stop execution upon a notice/warning, globally?
We run a development server with a lot of sites on, but want to force our developers to fix these warnings/notices (or ask for help with them at least) instead of ignoring and moving on.
Yes, it is possible. This question speaks to the more general issue of how to handle errors in PHP. You should define and register a custom error handler using set_error_handler
docs to customize handling for PHP errors.
IMHO it's best to throw an exception on any PHP error and use try/catch blocks to control program flow, but opinions differ on this point.
To accomplish the OP's stated goal you might do something like:
function errHandle($errNo, $errStr, $errFile, $errLine) {
$msg = "$errStr in $errFile on line $errLine";
if ($errNo == E_NOTICE || $errNo == E_WARNING) {
throw new ErrorException($msg, $errNo);
} else {
echo $msg;
}
}
set_error_handler('errHandle');
The above code will throw an ErrorException
any time an E_NOTICE
or E_WARNING
is raised, effectively terminating script output (if the exception isn't caught). Throwing exceptions on PHP errors is best combined with a parallel exception handling strategy (set_exception_handler
) to gracefully terminate in production environments.
Note that the above example will not respect the @
error suppression operator. If this is important to you, simply add a check with the error_reporting()
function as demonstrated here:
function errHandle($errNo, $errStr, $errFile, $errLine) {
if (!(error_reporting() & $errno)) {
// @ suppression used, don't worry about it
return;
}
// handle error here
}