PHP 8.5.0 Beta 1 available for testing

Voting

: min(five, four)?
(Example: nine)

The Note You're Voting On

devermin at ti0n dot net
15 years ago
At work I have some code with errors that uncatched are the causes of integrity loss (people calling web services with file_get_contents that fails silently and afterwards insert garbage in the database).

here is the solution I found to transform a specific set of errors into exception and afterwards be able to selectively act (with the error code) regarding categories :

<?php
ini_set
('error_reporting',E_ALL^E_NOTICE);

## first 10 bits reserved for the initial error number
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
## categories
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
## string error patterns => code

$catch_me=array(
"/^(file_get_contents)\((.*)\).*failed to open stream: (.*)/ " =>
array (
'mesg' => "IO::Failed to open stream with",
'code' => IOERROR | FAILURE
),
"/^fopen\(.*\): Filename cannot be empty/" =>
array(
'msg' => "Parameters::empty",
'code' => EMPTYPARMS
)
);
function
error_2_exception($errno, $errstr, $errfile, $errline,$context) {
global
$catch_me;
foreach (
$catch_me as $regexp => $res) {
if(
preg_match($regexp,$errstr,$match)){
throw new
Exception($res['mesg'],$res['code']|( $errno & EMASK ) );
}
}
/* switch back to PHP internal error handler */
return false;
}
## => want to catch this one
$f=file_get_contents("mlsdkfm");
## dont want to break existing wrong behaviour yet (so not caught)
$f=file_get_contents('');
## magic
set_error_handler("error_2_exception");
## behaviour remains the same
$f=file_get_contents('');
try {
## web services that dont work now raise an exception \o/
$f=file_get_contents("mlsdkfm");
} catch(
Exception $e) {
## and I can group my exception by category
echo ( $e->getCode() & FAILURE ) ? "\nEPIC FAIL\n" : "\nbegnine";
}

?>

<< Back to user notes page

To Top