8.16. Tuning Error Handling8.16.1. ProblemYou want to alter the error-logging sensitivity on a particular page. This lets you control what types of errors are reported. 8.16.2. SolutionTo adjust the types of errors PHP complains about, use error_reporting( ): error_reporting(E_ALL); // everything error_reporting(E_ERROR | E_PARSE); // only major problems error_reporting(E_ALL & ~E_NOTICE); // everything but notices 8.16.3. DiscussionEvery error generated has an error type associated with it. For example, if you try to array_pop( ) a string, PHP complains that "This argument needs to be an array," since you can only pop arrays. The error type associated with this message is E_NOTICE, a nonfatal runtime problem. By default, the error reporting level is E_ALL & ~E_NOTICE, which means all error types except notices. The & is a logical AND, and the ~ is a logical NOT. However, the php.ini-recommended configuration file sets the error reporting level to E_ALL, which is all error types. Error messages flagged as notices are runtime problems that are less serious than warnings. They're not necessarily wrong, but they indicate a potential problem. One example of an E_NOTICE is "Undefined variable," which occurs if you try to use a variable without previously assigning it a value: // Generates an E_NOTICE foreach ($array as $value) { $html .= $value; } // Doesn't generate any error message $html = ''; foreach ($array as $value) { $html .= $value; } In the first case, the first time though the foreach, $html is undefined. So, when you append to it, PHP lets you know you're appending to an undefined variable. In the second case, the empty string is assigned to $html above the loop to avoid the E_NOTICE. The previous two code snippets generate identical code because the default value of a variable is the empty string. The E_NOTICE can be helpful because, for example, you may have misspelled a variable name: foreach ($array as $value) { $hmtl .= $value; // oops! that should be $html } $html = '' foreach ($array as $value) { $hmtl .= $value; // oops! that should be $html } A custom error-handling function can parse errors based on their type and take an appropriate action. A complete list of error types is shown in Table 8-2. Table 8-2. Error types
Errors labeled catchable can be processed by the function registered using set_error_handler( ) . The others indicate such a serious problem that they're not safe to be handled by users, and PHP must take care of them. 8.16.4. See AlsoRecipe 8.17 shows how to set up a custom error handler; documentation on error_reporting( ) at http://www.php.net/error-reporting and set_error_handler( ) at http://www.php.net/set-error-handler; for more information about errors, see http://www.php.net/manual/en/ref.errorfunc.php. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|