how to make php exit on E_NOTICE?

前端 未结 2 1727
暖寄归人
暖寄归人 2021-01-04 19:56

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

相关标签:
2条回答
  • 2021-01-04 20:03

    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);
    
    }
    
    0 讨论(0)
  • 2021-01-04 20:22

    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

    0 讨论(0)
提交回复
热议问题