Home  >  Article  >  Backend Development  >  PHP error handling experience sharing_PHP tutorial

PHP error handling experience sharing_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:24:111289browse

This tutorial covers some of the most important error detection methods in PHP.

We will explain different error handling methods to you:

Simple "die()" statement
Custom errors and error triggers
Error reporting
Basic Error handling: using the die() function
The first example shows a simple script to open a text file:

Copy the code The code is as follows:

$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 In order to avoid users getting error messages like the above, we check whether the file exists before accessing it:
Copy code The code is as follows:

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

现在,假如文件不存在,您会得到类似这样的错误消息:

File not found比起之前的代码,上面的代码更有效,这是由于它采用了一个简单的错误处理机制在错误之后终止了脚本。

不过,简单地终止脚本并不总是恰当的方式。让我们研究一下用于处理错误的备选的 PHP 函数。
创建自定义错误处理器
创建一个自定义的错误处理器非常简单。我们很简单地创建了一个专用函数,可以在 PHP 中发生错误时调用该函数。

该函数必须有能力处理至少两个参数 (error level 和 error message),但是可以接受最多五个参数(可选的:file, line-number 以及 error context):

语法
error_function(error_level,error_message,
error_file,error_line,error_context)
参数 描述
error_level

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

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

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

错误报告级别

这些错误报告级别是错误处理程序旨在处理的错误的不同的类型:

常量 描述
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 的一部分)

Now, let’s create a function that handles errors:
Copy the code The code is as follows:

function customError($errno, $ errstr)
{
echo "Error: [$errno] $errstr
";
echo "Ending Script";
die() ;
}

The above code is a simple error handling function. When it is triggered, it gets the error level and error message. It then prints the error level and message, and terminates the script.

Now that we have created an error handling function, we need to determine when to fire it.
Set Error Handler
PHP’s default error handler is the built-in error handler. We are going to transform the above function into the default error handler when the script is running.

The error handler can be modified so that it only applies to certain errors, so that the script can handle different errors in different ways. However, in this case, we are going to use our custom error handler for all errors:

set_error_handler("customError"); Since we want our custom function to handle all errors, set_error_handler( ) requires only one argument, a second argument can be added to specify the error level.

Example
Test this error handler by trying to output a variable that does not exist:
Copy code The code is as follows:

//error handler function
function customError($errno, $errstr)
{
echo "Error:}

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

//trigger error
echo($ test);
?>

The output of the above code should be similar to this:

Error: [8] Undefined variable: test triggers the error
User in the script The location of the input data, useful for triggering an error when the user's input is invalid. In PHP, this task is accomplished by trigger_error().

Example
In this example, if the "test" variable is greater than "1", an error will occur:
Copy code The code is as follows:

$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below ");
}
?>

The output of the above code should be similar to this:

Notice: Value must be 1 or below
in C: webfoldertest.php on line 6 You can trigger errors anywhere in the script. By adding a second parameter, you can specify the error level that is triggered.

Possible error types:
E_USER_ERROR - fatal user-generated run-time error. The error cannot be recovered. Script execution was interrupted.
E_USER_WARNING - Non-fatal user-generated run-time warning. Script execution is not interrupted.
E_USER_NOTICE - Default. User-generated run-time notifications. The script found a possible error, which may have occurred while the script was running normally.
Example
In this example, if the "test" variable is greater than "1", the E_USER_WARNING error occurs. If an E_USER_WARNING occurs, we will use our custom error handler and end the script:
Copy the code The code is as follows:

//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $ errstr
";
echo "Ending Script";
die();
}

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

//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>

The output of the above code should look like this:

Error: [512] Value must be 1 or below
Ending Script now , we have learned how to create our own errors and how to punish them, now let's study error records.
Error logging
By default, PHP sends error logging to the server's error logging system or file according to the error_log configuration in php.ini. By using the error_log() function, you can send error records to a specified file or remote destination.

Emailing yourself an error message is a great way to get notified of a specified error.

Send error message via Email
In the example below, if a specific error occurs, we will send an email with an error message and end the script:
Copy code The code is as follows:

//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr
";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>

The output of the above code should be similar to this:

Error: [512] Value must be 1 or below
Webmaster has been notifiedThe email received from the above code should be similar to this:

Error: [512] Value must be 1 or below This method is not suitable for all errors. General errors should be logged on the server using the default PHP logging system.

Error backtrace


Definition and usage
The PHP debug_backtrace() function generates a backtrace.

This function returns an associative array. The following elements may be returned:
Name Type Description
function String Current function name.
line Integer Current line number.
file String The current file name.
class 字符串 当前的类名
object 对象 当前对象。
type 字符串 当前的调用类型,可能的调用:
  • 返回: "->"  - 方法调用
  • 返回: "::"  - 静态方法调用
  • 返回 nothing - 函数调用
args 数组 如果在函数中,列出函数参数。如果在被引用的文件中,列出被引用的文件名。
语法
debug_backtrace()例子
复制代码 代码如下:

function one($str1, $str2)
{
two("Glenn", "Quagmire");
}
function two($str1, $str2)
{
three("Cleveland", "Brown");
}
function three($str1, $str2)
{
print_r(debug_backtrace());
}

one("Peter", "Griffin");
?>

输出:

Array
(
[0] => Array
(
[file] => C:webfoldertest.php
[line] => 7
[function] => three
[args] => Array
(
[0] => Cleveland
[1] => Brown
)
)
[1] => Array
(
[file] => C:webfoldertest.php
[line] => 3
[function] => two
[args] => Array
(
[0] => Glenn
[1] => Quagmire
)
)
[2] => Array
(
[file] => C:webfoldertest.php
[line] => 14
[function] => one
[args] => Array
(
[0] => Peter
[1] => Griffin
)
)
)

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/324359.htmlTechArticle本教程介绍了 PHP 中一些最为重要的错误检测方法。 我们将为您讲解不同的错误处理方法: 简单的 "die()" 语句 自定义错误和错误触发器 错...
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