Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make php exit on E_NOTICE?

Normally php script continues to run after E_NOTICE, is there a way to elevate this to fatal error in context of a function, that is I need only to exit on notice only in my functions but not on core php functions, that is globally.

like image 731
rsk82 Avatar asked Aug 13 '11 11:08

rsk82


2 Answers

You could create a custom error handler to catch E_NOTICEs.

This is untested but should go into the right direction:

function myErrorHandler($errno, $errstr, $errfile, $errline)
 {
  if ($errno == E_USER_NOTICE)
   die ("Fatal notice");
  else
   return false; // Leave everything else to PHP's error handling

 }

then, set it as the new custom error handler using set_error_handler() when entering your function, and restore PHP's error handler when leaving it:

function some_function()
{

// Set your error handler
$old_error_handler = set_error_handler("myErrorHandler");

... do your stuff ....

// Restore old error handler
set_error_handler($old_error_handler);

}
like image 146
Pekka Avatar answered Sep 29 '22 21:09

Pekka


You use a custom error handler using set_error_handler()

<?php

    function myErrorHandler($errno, $errstr, $errfile, $errline) {
        if ($errno == E_USER_NOTICE) {
            die("Died on user notice!! Error: {$errstr} on {$errfile}:{$errline}");
        }
        return false; //Will trigger PHP's default handler if reaches this point.
    }

    set_error_handler('myErrorHandler');

    trigger_error('This is a E_USER_NOTICE level error.');
    echo "This will never be executed.";


?>

Working Example

like image 35
Madara's Ghost Avatar answered Sep 29 '22 19:09

Madara's Ghost