Latest web development tutorials

PHP set_error_handler () function

PHP Error Reference Complete PHP Error Reference

Definition and Usage

set_error_handler () function sets the error handling user-defined function.

This function is used to create a user during run their own error handling.

This function returns the old error handler if it fails to return NULL.

grammar

set_error_handler(error_function,error_types)

参数 描述
error_function 必需。规定发生错误时运行的函数。
error_types 可选。规定在哪个错误报告级别会显示用户定义的错误。默认是 "E_ALL"。可能的错误报告级别详见下面的表格。

error_function

grammar

error_function(error_level,error_message,
error_file,error_line,error_context)

参数 描述
error_level 必需的。规定用户自定义的错误的错误报告级别。必须是值数字。可能的错误报告级别详见下面的表格。
error_message 必需的。规定用户自定义的错误的错误消息。
error_file 可选。规定发生错误的文件名。
error_line 可选。规定发生错误的行号。
error_context 可选。规定指向活跃符号表中发生错误的数组。换句话说,error_context 将包含一个说明每个变量引发错误的存在范围的数组。

Error reporting level

常量 描述
2 E_WARNING 运行时非致命的错误。没有停止执行脚本。
8 E_NOTICE 运行时的通知。脚本发现可能是一个错误,但也可能在正常运行脚本时发生。
256 E_USER_ERROR 用户生成的致命错误。这就如同由程序员使用 PHP 函数 trigger_error() 生成的 E_ERROR。
512 E_USER_WARNING 用户生成的非致命错误。这就如同由程序员使用 PHP 函数 trigger_error() 生成的 E_WARNING。
1024 E_USER_NOTICE 用户生成的通知。这就如同由程序员使用 PHP 函数 trigger_error() 生成的 E_NOTICE。
4096 E_RECOVERABLE_ERROR 可捕获的致命错误。这就如同一个可以由用户定义的句柄捕获的 E_ERROR(见 set_error_handler())。
8191 E_ALL 所有的错误和警告的级别,除了 E_STRICT(自 PHP 6.0 起,E_STRICT 将作为 E_ALL的一部分)。


Tips and Notes

Tip: If youuse this function, completely bypassing the standard PHP error handler. If necessary, the user-defined error handler must terminate script (die ()).

NOTE: If an error occurs before the script executes, because the custom program has not been registered at that time, and therefore will not use this custom error handler.


Examples

<?php
//error handler function
function customError($errno, $errstr, $errfile, $errline)
{
echo "<b>Custom error:</b> [$errno] $errstr<br />";
echo " Error on line $errline in $errfile<br />";
echo "Ending Script";
die();
}

//set error handler
set_error_handler("customError");

$test=2;

//trigger error
if ($test>1)
{
trigger_error("A custom error has been triggered");
}
?>

The output of the code above is as follows:

Custom error:[1024] A custom error has been triggered
Error on line 19 in C:webfoldertest.php
Ending Script


PHP Error Reference Complete PHP Error Reference