note 98051 added to function.set-error-handler

From: Date: Sun, 23 May 2010 10:46:50 +0000
Subject: note 98051 added to function.set-error-handler
Groups: php.notes 
Request: Send a blank email to php-notes+get-169530@lists.php.net to get a copy of this message
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 : <? 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"; } ?> ---- Server IP: 89.31.146.176 Probable Submitter: 213.41.242.148 ---- Manual Page -- http://www.php.net/manual/en/function.set-error-handler.php Edit -- https://master.php.net/note/edit/98051 Del: integrated -- https://master.php.net/note/delete/98051/integrated Del: useless -- https://master.php.net/note/delete/98051/useless Del: bad code -- https://master.php.net/note/delete/98051/bad+code Del: spam -- https://master.php.net/note/delete/98051/spam Del: non-english -- https://master.php.net/note/delete/98051/non-english Del: in docs -- https://master.php.net/note/delete/98051/in+docs Del: other reasons-- https://master.php.net/note/delete/98051 Reject -- https://master.php.net/note/reject/98051 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#169530) next »