PHP error handling issues
PHP’s error handling mechanism
PHP’s error handling is relatively complicated. This article explains all the important knowledge points related to errors in PHP to make it easier to understand PHP’s error mechanism.
Basic knowledge
Before this, familiarize yourself with the basic knowledge of php error
Predefined constants
Runtime Configuration
Exception
Error handling function
Predefined constants
Defines all PHP error type constants. Each constant is an integer value. Its function is that the value (numeric value or symbol) above
is used to create a binary bit mask to Specify the error message to be reported. You can use bitwise operators to combine these values or to mask certain types of errors. Please note that in php.ini, only '|', '~', '!', '^' and '&' will be parsed correctly.
From the perspective of usage, it can be divided into three categories:
thrown manually by the user
E_USER_NOTICE
,E_USER_WARNING
,E_USER_ERROR
,E_USER_DEPRECATED
User-caused
E_NOTICE
,E_PARSE
,E_WARNING
,E_ERROR
,E_COMPILE_ERROR
,E_COMPILE_WARNING
,E_STRICT
,E_RECOVERABLE_ERROR
E_CORE_ERROR
,E_CORE_WARNING
caused by the php kernel From the perspective of whether to terminate program execution, it can be divided into two categories
Termination of program execution
The program terminates and enters the error handling processDoes not terminate program execution
An error occurs, but the program can still continue to execute and also enter the error handling process
For error types in PHP, you can refer to this more detailed article- -Summary of PHP's error mechanism
Runtime configuration
Manual--The runtime configuration is explained in detail, but there are several configurations that still require special attention
-
error_reporting
Reporting error type, it is recommended to configureE_ALL
in the development/testing environment. After solving all types of errors, configureE_ALL in the production environment & E_DEPRECATED
, indicates: report all errors except discarded errors ##display_errors
Whether to display errors, configure it to false in the production environment , combined with the settings of
error_reportingabove, it means: report all errors except discarded errors, but do not display error messages.
- ##log_errors
Whether error logging is turned on,
The production environment needs to be turned on
. With the above two configurations, it means: report all errors except discarded errors, do not display error messages, but record (only PHP itself can Operation error information) to the log. - error_log
Specify the error file
(syslog is a special value)
. The default is not Settings, in the manual:
If this configuration is not set, error messages will be sent to the SAPI error loggerReport all errors except discard errors, do not display error information, but record it to theGenerally, if not set, it will be recorded in the apache/nginx error log. With the above three configurations, it means: report all errors except obsolete errors, do not display error information, but record it in the apache/nginx log Medium. If the file path is configured, it means:
file_dirlog.
The above configurations affect the most basic performance of php errors. Of course, these configurations can be changed in the code through
or php-fpm configuration changesError handling function
There are not many error functions. The ones you should pay most attention to are
set_error_handler and set_exception_handler
, because they can intervene in the error/exception processing process.
Let’s first look at the explanation in the PHP manual: Errors
In simple terms That is,
The default processing flow is completed through configuration, but we can set a custom error handling flowHow to handle errors that terminate script execution
As mentioned in the article, there are two kinds of errors. So how to deal with this kind of error that will terminate the execution of the script?
set_error_handler
cannot handle this kind of error, which is easy to be ignored. So we need to find another One method.This problem is basically solved like this (have not seen other solutions yet):
// 终止脚本的错误会终止脚本执行 // 即会调用已通过register_shutdown_function注册的处理函数 // 由此可注册我们的错误处理流程, 这样就进入了自定义错误流程 register_shutdown_function('FatalErrorHandle'); ... FatalErrorHandle(array $error = null) { ... if (null === $error) { // 通过这种方式可以获取最后一条错误 $error = error_get_last(); } ... // log or other logic }
Exception
According to the explanation in w3cPHP exception handling:
Exception handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception.When an exception is triggered, what usually happens is:
The current code state is saved
- Code execution is switched to the predefined Exception handler function
Depending on the situation, the processor may restart code execution from a saved code state, terminate script execution, or continue script execution from a location outside the code
Uncaught exceptions will terminate script execution and generate an E-ERROR error. The defined exception handling will be performed. If not, the default error handling process of PHP will be performed, which is recorded in the log. However, in terms of programming concepts, it should be Separate exceptions from errors. Exceptions are predictable to users, do not meet expectations, and are controllable structures.
set_exception_handler
mentioned above is used to handle exceptions. Usage Consistent with set_error_handler
. The exception handling in each framework is very mature. Generally speaking, set_exception_handler
will transfer Exception
to the framework handleable level, and the framework will also Open good interfaces for users to use, so as to achieve the purpose of user control of exception handling and realize customization and expansion.
Summary
php's error handling mechanism is always ignored, but it is useful for debugging. Monitoring errors plays a great role. This article mainly introduces the main knowledge points and makes a summary. I hope it will be useful to everyone. For more details, please check the manual.
Learning Materials
Predefined constants
Runtime configuration
Error handling function
Summary of PHP's error mechanism
Exceptions
Errors
PHP exception handling
Symfony Debug: is a complete application , it can be said to be a comprehensive tutorial, covering all error-related knowledge points. It is recommended to read the source code.
The above is the detailed content of PHP error handling issues. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
