Recipe 20.8. Using a Custom Error Handler

20.8.1. Problem

You want to create a custom error handler that lets you control how PHP reports errors.

20.8.2. Solution

To set up your own error function, use set_error_handler( ):

set_error_handler('pc_error_handler'); function pc_error_handler($errno, $error, $file, $line) {     $message = "[ERROR][$errno][$error][$file:$line]";     error_log($message); }

20.8.3. Discussion

A custom error handling function can parse errors based on their type and take the appropriate action. See Table 20-2 in Recipe 20.7 for a list of error types.

Pass set_error_handler( ) the name of a function, and PHP forwards all errors to that function. The error handling function can take up to five parameters. The first parameter is the error type, such as 8 for E_NOTICE. The second is the message thrown by the error, such as "Undefined variable: html." The third and fourth arguments are the name of the file and the line number in which PHP detected the error. The final parameter is an array holding all the variables defined in the current scope and their values.

For example, in this code, $html is appended to without first being assigned an initial value:

error_reporting(E_ALL); set_error_handler('pc_error_handler'); function pc_error_handler($errno, $error, $file, $line, $context) {     $message = "[ERROR][$errno][$error][$file:$line]";     print "$message";     print_r($context); } $form = array('one','two'); foreach ($form as $line) {     $html .= "<b>$line</b>"; }

When the "Undefined variable" error is generated, pc_error_handler( ) prints:

[ERROR][8][Undefined variable:  html][err-all.php:16]

After the initial error message, pc_error_handler( ) also prints a large array containing all the globals, environment, request, and session variables.

Errors labeled catchable in Table 20-2 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.

20.8.4. See Also

Recipe 20.7 lists the different error types; documentation on set_error_handler( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: