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() == 0) {
// @ suppression used, don't worry about it
return;
}
// handle error here
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…