How to catch undefined functions with set_error_handler in PHP

后端 未结 6 499
一整个雨季
一整个雨季 2021-02-05 19:47

I\'m taking the leap: my PHP scripts will ALL fail gracefully!

At least, that\'s what I\'m hoping for...`

I don\'t want to wrap (practically) every single line i

6条回答
  •  误落风尘
    2021-02-05 20:47

    set_error_handler is designed to handle errors with codes of: E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE. This is because set_error_handler is meant to be a method of reporting errors thrown by the user error function trigger_error.

    However, I did find this comment in the manual that may help you:

    "The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

    This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

     $string)
            $output .= "{$info}: {$string}\n";
        return $output;
    }
    
    ob_start('error_handler');
    
    will_this_undefined_function_raise_an_error();
    
    ?>
    

    Really though these errors should be silently reported in a file, for example. Hopefully you won't have many E_PARSE errors in your project! :-)

    As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.

提交回复
热议问题