You are here: Home » Tutorials » Web Development » PHP » Error Handling » How to create a Custom Error Handler in PHP..

How to create a Custom Error Handler in PHP

Added January 27, 2008, read 1965 times

Using a Custom Error Handler

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

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

PHP Code
set_error_handler('pc_error_handler');

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

A custom error handling function can parse errors based on their type and take the appropriate action. Here is a list of error types.

Value Constant Description Catchable
1 E_ERROR Nonrecoverable error No
2 E_WARNING Recoverable error Yes
4 E_PARSE Parser error No
8 E_NOTICE Possible error Yes
16 E_CORE_ERROR Like E_ERROR but generated by the PHP core No
32 E_CORE_WARNING Like E_WARNING but generated by the PHP core No
64 E_COMPILE_ERROR Like E_ERROR but generated by the Zend Engine No
128 E_COMPILE_WARNING Like E_WARNING but generated by the Zend Engine No
256 E_USER_ERROR Like E_ERROR but triggered by calling trigger_error( ) Yes
512 E_USER_WARNING Like E_WARNING but triggered by calling trigger_error( ) Yes
1024 E_USER_NOTICE Like E_NOTICE but triggered by calling trigger_error( ) Yes
2047 E_ALL Everything except E_STRICT N/A
2048 E_STRICT Runtime notices in which PHP suggests changes to improve code quality (since PHP 5) N/A

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:

PHP Code
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>";
}
Select all

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

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

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

Discuss

  • Your name
  • Your email (we'll keep this to ourselves)
  • What's it about?
  • Security check

Nobody posted any comments regarding this story. Be the first!