Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop script execution upon notice/warning

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.

like image 661
Michael Avatar asked May 09 '12 16:05

Michael


People also ask

Does a PHP warning stop execution?

Your answer is missing the "stop execution" part of the question. Setting the error reporting will only affect output (either on screen or into a log), but only errors or fatals will stop the script - warnings and notices will not.

How to fix notice error in PHP?

Open php. ini file in your favourite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE. Now your PHP compiler will show all errors except 'Notice.


1 Answers

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_handlerdocs 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 } 
like image 180
rdlowrey Avatar answered Sep 17 '22 10:09

rdlowrey