Get all PHP errors/warnings/… that occurred during the current request

后端 未结 5 1752
野性不改
野性不改 2021-02-13 18:07

Setting the directive display_errors to true (while having error_reporting set to E_ALL) prints all errors that occured durin

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-13 18:52

    Referring to your first concern

    The error handling will still work as long as the:

    callback function returns FALSE

    function myErrorHandler($error_level, $error_message, $error_file, $error_line, $error_context) {
        // Do your stuff here, e.g. saving messages to an array
    
        // Tell PHP to also run its error handler
        return false;
    }
    

    One solution to store all error-numbers (in an outside array $error_list) could be:

    $error_list = array();
    
    $myErrorHandler = function ($error_level, $error_message, $error_file, $error_line, $error_context) use (&$error_list) {
        $error_list[] = $error_level;
        // Tell PHP to also run its error handler
        return false;
    };
    // Set your own error handler
    $old_error_handler = set_error_handler($myErrorHandler);
    

    Another approach is to use Exceptions. There is a nice example in the comments for the function set_error_handler()

    Also see:

    • Are global variables in PHP considered bad practice? If so, why?
    • PHP: Callback function using variables calculated outside of it

    Referring to your second concern:

    As Egg already mentioned: using register_shutdown_function() is a way to go, and the code in the answer https://stackoverflow.com/a/7313887/771077 shows you how.

    But keep in mind, that

    • Registering the shutdown- and error-handling functions should be the first thing in code (I fool once had an error in a config file, which was not handled correct, since I registered the error handler afterwards).
    • Parse errors might not be handled correctly (See comment in https://stackoverflow.com/a/7313887/771077)

提交回复
热议问题