Home >Backend Development >PHP Tutorial >PHP Core Features - Error Handling

PHP Core Features - Error Handling

PHPz
PHPzforward
2016-07-28 08:30:171153browse

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 case by catching the exception, but before the exception is caught, PHP triggers the error.

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

In other words, PHP triggers the case of division by 0 as an error, and does 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 the if - else statement and combined with the throw method.

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

Error levels

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

● Parse error or Syntax Error - syntax parsing error, After this error is triggered, the script cannot run at all;
● Fatal Error - fatal error, after this error is triggered, subsequent scripts cannot continue to execute;
●Warning Error - when an inappropriate place occurs, the script can continue to execute;
●Notice Error - Inappropriate place occurs, but the degree is lower than Warning Error, the script can continue to execute;
●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 display the error level and corresponding prompts.

Parse Error Example - No semicolon at the end of the statement
echo "abc"
// PHP Parse error: syntax error, unexpected end of file, expecting ',' or ';
Fatal Error Example - Using a non-existent function
echo "beforen";
foo();
echo "after"; // This line cannot continue to execute
// before
// PHP Fatal error: Uncaught Error: Call to undefined function foo()
Warning Error Example- Introducing non-existent files
$a = "foo";
include('bar.php');
echo $a; // The program continues to execute
// PHP Warning: include(bar.php): failed to open stream : No such file or directory ...
// foo
Notice Error Example - Output non-existing variable
echo $foo;
echo 12345;
// PHP Notice: Undefined variable: foo
// 12345
Deprecated Error Example - Pass numbers instead of strings in some string functions
strpos('12345', 3);
// PHP Deprecated: strpos(): Non-string needles will be interpreted as strings in the future

except In addition to the default trigger message, users can also use The set_error_handler function customizes error handling. Most error types can be customized, except E_ERROR, E_PARSE, Except 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

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

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);

Error-related configurations

Some common configurations related to error handling
● error_reporting - Set the error reporting level
● display_errors - Whether to display errors
● display_startup_error - Whether to display the display during PHP startup process
● log_errors - Set whether to record script running error information to the server error log or error_log

"Modern PHP" proposes four rules

● Be sure to let PHP report errors;
● In the development environment Display errors;
● Errors cannot be displayed in the production environment;
● Record errors 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

Recommended configuration for the production environment

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

Symfony coding specification related

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

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

When the error type is E_USER_DEPRECATED, @

@trigger_error("foo", E_USER_DEPRECATED);
needs to be added
Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete