Home > Article > Backend Development > Systematically understand errors and exceptions in PHP
One of the reasons why the PHP language is simple is the error handling mechanism of PHP. As the PHP language becomes more and more modern, exceptions also occur. This blog post simply talks about errors and exceptions to facilitate the understanding of the system. In addition, for any For a language, the existence of exceptions is common, so it is essential to learn a language and understand the exception mechanism.
What is an error
When When the PHP language encounters an abnormal situation (such as database connection failure or function parameter transfer error), some errors will be reported. Errors can be divided into various 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 does not frequently report errors, giving people the illusion of smooth and convenient writing.
It is also for this reason that PHP programs are rigorous and accurate The performance is 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, then the program is essentially wrong.
Through PHP. We can choose what type of errors to report through the error_reporting instruction of ini or dynamically call the error_reporting() function. Through the display_errors instruction, we can control whether errors are output online. The error_log instruction can control the output of errors to the log.
How to use errors correctly
Whether it is a system function or a custom function, if an error is encountered internally, how do you notify the caller? This is usually indicated by the function returning TRUE or FALSE. This This processing method has several disadvantages:
● The caller only knows that an error occurred, but the error information returned is too little and lacks description of the error type
● Program processing logic and error handling Mixed together, the generated code will be very unclear.
A little trick: the error_get_last() function will return the specific cause of the recent error.
Best practice:
● set_error_handler() function to host all errors
● trigger_error() function can trigger custom errors and can be used to replace the return statement in the function
● Output all errors to the log and define error types
● Display errors to users, such as returning errors to users in a more friendly way
● display_errors in production environment The command should be closed, and the development environment should be opened by this command
The old PHP framework Codeigniter's way of handling errors can be used for reference
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 It 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 catch them. In this way, developers can perform subsequent processing based on specific errors. For example, they can return friendly prompts 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 directly Terminated.
● Another action for exceptions is to throw. If you write business logic through functions and encounter unexpected situations, you can directly throw an exception.
● Exceptions can be thrown by the code. Capture layer by layer, if the outermost program has not caught it, 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
Explain through intuitive code:
function inverse($x) { if ($x < 10) { throw new Exception('x<10'); } elseif ($x >= 10 and $x < 100) { throw new LogicException('x>=10 and x<100'); } return $x; } try { echo inverse(2)."\n"; } catch (LogicException $e) { echo 'Caught LogicException: ', $e->getMessage(), "\n"; } catch (Exception $e) { echo 'Caught Exception: ', $e->getMessage(), "\n"; throw $e; }
Best practices for exceptions
● Exceptions can make the code clearer and allow developers to focus on business logic Writing.
● Building extensible exceptions is very technical. Isn’t SPL exception not enough?
● Catching exceptions should only capture exceptions that can be handled by this layer. For exceptions that cannot be handled, The handled exceptions are handled by the upstream code.
Exceptions in PHP7
PHP7 encourages the use of exceptions to replace errors, but it is impossible to overturn the error handling mechanism all at once. It needs to be compatible, so we can only transition slowly.
But exceptions can be used uniformly through flexible methods
● Error exception
defined in PHP An Error exception was raised. 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. This way we can happily Unified usage is abnormal.
The above is the detailed content of Systematically understand errors and exceptions in PHP. For more information, please follow other related articles on the PHP Chinese website!