Home > Backend Development > PHP Tutorial > Analyze PHP error handling (core feature)

Analyze PHP error handling (core feature)

藏色散人
Release: 2023-04-08 10:30:01
forward
2130 people have browsed it

Analyze PHP error handling (core feature)

Errors and exceptions

Errors can understand errors in the program itself, such as syntax errors. Exceptions tend to be when the program does not run as expected or does not conform to the normal process; for the PHP language, the mechanisms used to handle errors and exceptions are completely different, so it is easy to cause confusion.

For example, we want to handle the division by 0 situation by catching the exception, but before the exception is caught, PHP triggers an error.

try {
    $a = 5 / 0;
} catch (Exception $e) {
    $e->getMessage();
    $a = -1;  // 通过异常来处理 $a 为 0 的情况,但是实际上,捕获不到该异常
}

echo $a;
// PHP Warning:  Division by zero
Copy after login

That is to say, PHP will trigger the situation when the divisor is 0 as an error, and will not automatically throw an exception, so it cannot be caught. Similarly, in many cases, PHP cannot automatically throw exceptions. Exceptions can only be thrown manually through if-else statements and combined with the throw method.

The above situation occurs mainly because the exception mechanism is the product of PHP's evolution to object-oriented. Prior to this, PHP's error reporting was mainly through the error mechanism. Therefore, in many cases, PHP errors are more valuable than exceptions. However, PHP7 begins to unify the two, allowing errors to be thrown like exceptions (this part will be explained in the exceptions section).

Error level

Errors in PHP can be understood as abnormal situations that prevent the script from running properly. They can be determined from high to low according to the error level. Divided into five categories

1.Parse error or Syntax Error - syntax parsing error, after triggering this error, the script cannot run at all;

2.Fatal Error - Fatal error. After this error is triggered, subsequent scripts cannot continue to execute;

3.Warning Error - An inappropriate place appears. The script can continue to execute;

4.Notice Error - Something inappropriate has occurred, but the degree is lower than a Warning Error, the script can continue to execute;

5.Deprecated Error - This use is not recommended and may be abandoned in the future. The script can continue to execute;

By default, PHP triggers an error and displays the error level and corresponding prompt.

Parse Error Example - No semicolon at the end of the statement

 echo "abc"
// PHP Parse error:  syntax error, unexpected end of file, expecting ',' or ';
Copy after login

Fatal ErrorExample - Using a non-existent function

 echo "before\n";
 foo();
 echo "after"; // 本行无法继续执行
 // before
 // PHP Fatal error:  Uncaught Error: Call to undefined function foo()
Copy after login

Warning Error Example - Introducing non-existent file

$a = "foo";
include('bar.php');
echo $a; // 程序继续执行
// PHP Warning:  include(bar.php): failed to open stream: No such file or directory ...
// foo
Notice Error 示例 - 输出不存在的变量

echo $foo;
echo 12345;
// PHP Notice:  Undefined variable: foo
// 12345
Copy after login

Deprecated Error Example - In some string functions Pass in numbers instead of strings

 strpos('12345', 3);
 // PHP Deprecated:  strpos(): Non-string needles will be interpreted as strings in the future
Copy after login

In addition to the default trigger message, users can also use the set_error_handler function to customize error handling. Most error types can be customized, except Except for E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING .

 set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] ) : mixed
Copy after login

Example

<?php
// E_ALL - 处理全部错误类型
set_error_handler(&#39;customError&#39;, E_ALL);

/**
 * @param  int $errno 错误的级别
 * @param  string $errstr  错误的信息
 * @param  string $errfile 错误的文件名(可选)
 * @param  string $errline 错误发生的行号(可选)
 */
function customError(int $errno, string $errstr, string $errfile, string $errline)
{
    echo sprintf(&#39;错误消息为 %s&#39;, $errstr);
}

$a = 5 / 0;  // 错误消息为 Division by zero
Copy after login

Users can also manually trigger a user-level error (E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_USER_DEPRECATED) through the trigger_error function .

function division($a, $b) {
    if($b == 0){
        @trigger_error("0 不能作为除数", E_USER_NOTICE);
        return -1;
    }
    return $a / $b;
}

echo division(10, 0);
Copy after login

Error-related configuration

Some common configuration related to error handling

error_reporting - Set the error reporting level

display_errors - Whether to display errors

display_startup_error - Whether to display PHP startup Display during the process

log_errors -Set whether to record the error information of the script running to the server error log or error_log

"Modern PHP" proposes four Rules

● Be sure to let PHP report errors;

● Errors must be displayed in the development environment;

● Errors must not be displayed in the production environment;

● Errors must be recorded in both the development environment and the production environment;

Recommended configuration for the development environment

 display_errors = On
 display_startup_error = On
 error_reporting = -1
 log_errors = On
Copy after login

Recommended configuration for the production environment

display_errors = Off
display_startup_error = Off
; 报告 Notice 以外的所有错误
error_reporting = E_ALL & ~E_NOTICE
log_errors = On
Copy after login

Symfony encoding specification related

Exception and error message strings must be spliced ​​using sprintf ;

throw new CommandNotFoundException(sprintf('Command "%s" does not exist.', $name));

When the error type is E_USER_DEPRECATED, you need to add@

@trigger_error("foo", E_USER_DEPRECATED);

For more related php knowledge, please visit php tutorial!

The above is the detailed content of Analyze PHP error handling (core feature). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template