Home >Backend Development >PHP7 >Analyze errors and exceptions in PHP7 together

Analyze errors and exceptions in PHP7 together

藏色散人
藏色散人forward
2021-10-14 16:44:512253browse

Recommended: "PHP7 Tutorial"

The reason why PHP language is simple One of them is PHP's error handling mechanism. As the PHP language becomes more and more modern, exceptions also appear. This blog post simply talks about errors and exceptions to facilitate the system's understanding. In addition, for any language, exceptions There are commonalities, so it is essential to learn a language and understand the exception mechanism.

What is an error
When the PHP language encounters an abnormal situation (such as database connection (or function parameters are passed incorrectly), some errors will be reported. Errors can be divided into many types. Except for E_ERROR and E_CORE_ERROR errors, other errors will not terminate the program.
The reason why PHP makes people feel simple is that The program will not frequently report errors, giving people the illusion of smooth and convenient writing.
It is precisely for this reason that the rigor and accuracy of PHP programs are much worse. For example, when the mysql_fetch_array query encounters a network error and returns FALSE ( The program does not terminate running), if the calling program thinks that the query does not have matching data, the program is essentially wrong.
We can choose what type of errors to report through the error_reporting instruction in php.ini or dynamically calling the error_reporting() function. The display_errors command can control whether errors are output online. The error_log command can control the error output to the log.

How to use errors correctly
Whether it is a system function or a custom one If a function encounters an error internally, how does it notify the caller? It is usually indicated by the function returning TRUE or FALSE. This processing method has several disadvantages:
● The caller only knows that an error has occurred, but the returned There is too little error information and lack of description of the error type
● Program processing logic and error handling are mixed together, and the generated code will be very unclear.
A little trick: the error_get_last() function will return the most recent error. The specific reason.

Best practice:
● set_error_handler() function to host all errors
● The trigger_error() function can trigger custom errors and can be used Replace the return statement in the function
● Output all errors to the log and define the error type
● Display errors to users, such as returning errors to users in a more friendly way
● Production The display_errors command should be turned off in the environment and turned on in the development environment.
The old PHP framework Codeigniter can learn from the way it handles errors

`function _error_handler($severity, $message, $filepath, $line)
{
    $is_error = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $severity) === $severity);
    //输出500错误HTTP状态码
    if ($is_error) {
        set_status_header(500);
    }
    //对于不需要处理的错误则直接中断
    if (($severity & error_reporting()) !== $severity) {
        return;
    }
    //将所有的错误记录到日志中
    $_error =& load_class('Exceptions', 'core');
    $_error->log_exception($severity, $message, $filepath, $line);
    //友好的输出所有错误
    if (str_ireplace(array('off', 'none', 'no', 'false', 'null'), '', ini_get('display_errors'))){
        $_error->show_php_error($severity, $message, $filepath, $line);
    }
    //假如致命错误则直接退出
    if ($is_error) {
        exit(1);   
    }
}
set_error_handler('_error_handler');`

What is an exception
Exception is also an error , it has the following characteristics:
● Exceptions can be customized, SPL provides many types of exceptions, and you can also extend it
● The most common action for exceptions is to capture, so that developers can customize the exceptions based on specific errors. Carry out subsequent processing. For example, you can return a friendly prompt to the user based on the context of the exception. Or continue to throw an exception and let the upstream program handle it. If the exception is still not caught, the program will terminate directly.
● Exceptions in addition The first action is to throw. If you write business logic through functions and encounter unexpected situations, you can directly throw an exception.
● Exceptions can be caught by the code layer by layer. If the outermost program has not caught it yet, The code will terminate running directly
●If the exception in PHP cannot be caught, it will be written to the system error log as a fatal error
Illustrated through intuitive code:

`function inverse($x)
{
    if ($x < 10) {
        throw new Exception(&#39;x<10&#39;);
    } elseif ($x >= 10 and $x < 100) {
        throw new LogicException(&#39;x>=10 and x<100&#39;);
    }
    return $x;
}
try {
    echo inverse(2)."\n";
} catch (LogicException $e) {
    echo &#39;Caught LogicException: &#39;, $e->getMessage(), "\n";
} catch (Exception $e) {
    echo 'Caught Exception: ', $e->getMessage(), "\n";
    throw $e;
}`

Exception Best practices
● Exceptions can make the code clearer, allowing developers to focus on writing business logic.
● Building extensible exceptions is very technical. Isn’t SPL exception not enough? Is it?
● Catching exceptions should only capture exceptions that can be handled by this layer, and let upstream code handle exceptions that cannot be handled.

Exceptions in PHP7
PHP7 It is encouraged to use exceptions to replace errors, but it is impossible to overturn the error handling mechanism all at once. Compatibility is required, so the transition can only be made slowly.
But exceptions can be used uniformly through workarounds
● Error exception
PHP An Error exception is defined in. Note that this exception and Exception are juxtaposed.
When strict mode is turned on, many errors in PHP7 are thrown by Error exceptions. In this way, exceptions can be used uniformly.

`declare (strict_types = 1);
function add(int $a, int $b)
{
    return $a + $b;
}
try {
    echo add("3", "4");
}
catch (TypeError $e) { //TypeError继承自Error
    echo $e->getMessage();
}`

● ErrorException
ErrorException inherits from Exception.
We can convert all errors into ErrorException through the set_error_handler() function. In this way, we can use exceptions happily.
The above is a systematic understanding The details of errors and exceptions in PHP, I hope it will be helpful to you.
Read the original text: Systematic understanding of errors and exceptions in PHP

The above is the detailed content of Analyze errors and exceptions in PHP7 together. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete