Home  >  Article  >  Backend Development  >  PHP custom error handling function_PHP tutorial

PHP custom error handling function_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:11:041013browse

In PHP development, we generally use PHP's built-in error handling method to handle some errors, but for some we need to customize some error handling mechanisms to solve problems that the system's built-in system cannot solve.

Basic error handling: use the die() function
The first example shows a simple script that opens a text file:

The code is as follows Copy code
代码如下 复制代码
$file=fopen("welcome.txt","r");
?>
$file=fopen("welcome.txt","r");

?>

If the file does not exist, you will get an error like this:


Warning: fopen(welcome.txt) [function.fopen]: failed to open stream:

No such file or directory in C:webfoldertest.php on line 2 To avoid users getting error messages like the one above, we check whether the file exists before accessing it:
 代码如下 复制代码

if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>

The code is as follows Copy code
if(!file_exists("welcome.txt"))<🎜> {<🎜> die("File not found");<🎜> }<🎜> else<🎜> {<🎜> $file=fopen("welcome.txt","r");<🎜> }<🎜> ?>

Now, if the file does not exist, you will get an error message like this:

File not found The above code is more efficient than the previous code because it uses a simple error handling mechanism to terminate the script after the error.

However, simply terminating the script is not always appropriate. Let's examine alternative PHP functions for handling errors.

Let’s look at a custom error handling function

The code is as follows Copy code
 代码如下 复制代码

function myErrorHandler($errno, $errstr, $errfile, $errline){
    if(!(error_reporting() &$errno)){return;}
    switch ($errno){
    case E_USER_ERROR:
        echo "My ERROR [$errno] $errstr
";
        echo "错误行:$errline 在文件:$errfile之中
";
        echo " PHP版本: " .PHP_VERSION ." (" .PHP_OS .")
";
        break;
    case E_USER_WARNING:
        echo "My WARNING [$errno] $errstr
";
        break;
    case E_USER_NOTICE:
        echo "My NOTICE [$errno] $errstr
";
        break;
    default:
        echo "Unknown error type: [$errno] $errstr
";
        break;
    }
    return true;
}

function trigger_test($age){//抛出错误的测试函数
    if($age <= 0 || $age > 999) trigger_error("年龄不合法:$age岁", E_USER_ERROR);
    if($age < 18) trigger_error("未成年:$age岁", E_USER_WARNING);
if($age > 40 && $age < 100) trigger_error("年龄稍大:$age岁", E_USER_NOTICE);
}
//如果只是简单统一地处理错误:
$errorHandler = set_error_handler("myErrorHandler");
trigger_test(1000);//会抛出一个error级的错误


function myError($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    //具体处理方法
}
function myWarning($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    //具体处理方法
}

function myNtice($errno, $errstr, $errfile, $errline){
    print_r(func_get_args());
    //具体处理方法
}

function myErrorHandler($errno, $errstr, $errfile, $errline){
If(!(error_reporting() &$errno)){return;}
switch ($errno){
case E_USER_ERROR:
echo "My ERROR [$errno] $errstr
";
echo "Error line: $errline in file: $errfile
";
echo " PHP version: " .PHP_VERSION ." (" .PHP_OS .")
";
          break;
case E_USER_WARNING:
echo "My WARNING [$errno] $errstr
";
          break;
case E_USER_NOTICE:
echo "My NOTICE [$errno] $errstr
";
          break;
default:
echo "Unknown error type: [$errno] $errstr
";
          break;
}
Return true;
}

function trigger_test($age){//Test function that throws an error
If($age <= 0 || $age > 999) trigger_error("Illegal age: $age years old", E_USER_ERROR);
If($age < 18) trigger_error("Underage: $age years old", E_USER_WARNING);
If($age > 40 && $age < 100) trigger_error("Slightly older: $age years old", E_USER_NOTICE);
}
//If you just handle errors simply and uniformly:
$errorHandler = set_error_handler("myErrorHandler");
trigger_test(1000);//will throw an error level error
 代码如下 复制代码
set_error_handler('myError',E_USER_ERROR);
set_exception_handler('myWarning',E_USER_WARNING);
set_exception_handler('myNtice',E_USER_NOTICE);

function myError($errno, $errstr, $errfile, $errline){
Print_r(func_get_args());
//Specific processing method
}
function myWarning($errno, $errstr, $errfile, $errline){
Print_r(func_get_args());
//Specific processing method
} function myNtice($errno, $errstr, $errfile, $errline){
Print_r(func_get_args());
//Specific processing method
}
//If you want to handle different error levels separately:

trigger_error('Intentionally throwing an error, or a serious one!', E_USER_ERROR);

Attached below are some detailed explanations of some PHP error codes

Parameters Description
参数 描述
error_level

必需。为用户定义的错误规定错误报告级别。必须是一个值数。

参见下面的表格:错误报告级别。

error_message 必需。为用户定义的错误规定错误消息。
error_file 可选。规定错误在其中发生的文件名。
error_line 可选。规定错误发生的行号。
error_context 可选。规定一个数组,包含了当错误发生时在用的每个变量以及它们的值。
error_level

Required. Specifies the error reporting level for user-defined errors. Must be a value.

See table below: Error reporting levels.

常量 描述
2 E_WARNING 非致命的 run-time 错误。不暂停脚本执行。
8 E_NOTICE

Run-time 通知。

脚本发现可能有错误发生,但也可能在脚本正常运行时发生。

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 的一部分)

error_message Required. Specifies error messages for user-defined errors. error_file Optional. Specifies the name of the file in which the error occurred.

error_line Optional. Specifies the line number where the error occurred. error_context Optional. Specifies an array containing each variable in use when the error occurred and their values. Error reporting level These error reporting levels are different types of errors that error handlers are designed to handle: http://www.bkjia.com/PHPjc/629638.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629638.htmlTechArticleIn PHP development, we generally use PHP’s own error handling method to handle some errors, but there are some we need Customize some error handling mechanisms to solve problems that the system cannot solve...
value Constant Description
2 E_WARNING Nonfatal run-time error. Do not pause script execution.
8 E_NOTICE Run-time notification. Script discovery errors may occur, but may also occur while the script is running normally.
256 E_USER_ERROR Fatal user-generated error. This is similar to E_ERROR set by the programmer using the PHP function trigger_error().
512 E_USER_WARNING Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error().
1024 E_USER_NOTICE User-generated notifications. This is similar to E_NOTICE set by the programmer using the PHP function trigger_error().
4096 E_RECOVERABLE_ERROR Catchable fatal error. Like E_ERROR, but can be caught by a user-defined handler. (see set_error_handler())
8191 E_ALL All errors and warnings except level E_STRICT. (In PHP 6.0, E_STRICT is part of E_ALL)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn