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);
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
$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 ) );
}
}
return false;
}
$f=file_get_contents("mlsdkfm");
$f=file_get_contents('');
set_error_handler("error_2_exception");
$f=file_get_contents('');
try {
$f=file_get_contents("mlsdkfm");
} catch(Exception $e) {
echo ( $e->getCode() & FAILURE ) ? "\nEPIC FAIL\n" : "\nbegnine";
}
?>