search
HomeBackend DevelopmentPHP TutorialPHP error handling mechanism, php processing mechanism_PHP tutorial

PHP error handling mechanism, php processing mechanism

In the daily project development process, there will always be some unexpected exception errors that we don’t expect. If we don’t deal with them, If the processing is perfect, the program will look very unprofessional and may become effective information for others to attack the system; some error exceptions will terminate the execution of the script. If there is no error message at this time, then we can only start from the beginning. Looking at the code, we need to know how terrifying it is for us to have hundreds or thousands of lines of code in the project. So how can we quickly and accurately locate exceptions and errors during the project development process, and make corresponding adjustments? Processing, this article is based on my own understanding of error and exception handling, and I will share it with everyone to learn from each other and serve as a memo.

System error handler:

Under normal circumstances in PHP, errors will be output normally, but in some frameworks, it may affect the error output. It may be that the framework itself has its own processing mechanism, or it may be processed in the code, usually these are Function settings:

1.error_reporting(); Set the error reporting level of PHP and return the current level

error_reporting(report_level)

If the parameter level is not specified, the current error level will be returned. The following are possible values ​​for level:

Value

Constant

Description

1

E_ERROR

Fatal runtime error. This error cannot be recycled. Script execution was interrupted.

2

E_WARNING

Non-fatal runtime warning. Script execution is not interrupted.

4

E_PARSE

Compile time analysis error. Parsing errors should only be generated by the parser

8

E_NOTICE

Runtime notification. The script found may be a bug, but it can also happen normally when running a script

16

E_CORE_ERROR

Fatal error when starting PHP. This is like the E_ERROR in the core of PHP

32

E_CORE_WARNING

Warn when PHP starts . This is like the E_WARNING in the core of PHP

64

E_COMPILE_ERROR

Fatal compile-time error. This is like passing the Zend script engine to generate the E_ERROR

128

E_COMPILE_WARNING

Non-fatal compile-time warning. This is like passing the Zend script engine to generate E_WARNING

256

E_USER_ERROR

Fatal user-generated error, similar to the one set by the programmer using the PHP function trigger_error() E_ERROR

512

E_USER_WARNING

Non-fatal user-generated warning, similar to one set by the programmer using the PHP function trigger_error E_WARNING

1024

E_USER_NOTICE

User-generated notifications, similar to those set by programmers using the PHP function trigger_error E_NOTICE

2048

E_STRICT

Runtime notification. PHPSuggest changes to your code to help with interoperability and compatibility of that code

4096

E_RECOVERABLE_ERROR

Catchable fatal error, similar to E_ERROR, but can be caught by user-defined handler (see set_error_handler())

8191

E_ALL

All errors and warnings except level E_STRICT (In PHP6.0, E_STRICT will be E_ALL part)

It is worth noting here that when $level is 0, error output is turned off, that is, no errors will be output.

2.set_error_handler()

Definition and usage

The set_error_handler() function sets a user-defined error handling function.

This function is used to create the user's own error handling method during runtime.

This function returns the old error handler, or null on failure.

Grammar

set_error_handler(error_function,error_types)

Parameters

参数

描述

error_function

必需。规定发生错误时运行的函数。

error_types

可选。规定在哪个错误报告级别会显示用户定义的错误。默认是 "E_ALL"。

Description

error_function

Required. Specifies the function to run when an error occurs.

error_types

Optional. Specifies at which error reporting level user-defined errors are displayed. The default is "E_ALL".

Tip: If this function is used, the standard PHP error handling functions are completely bypassed, and the user-defined error handler must terminate (die()) the script if necessary,

Note: If an error occurs before the script is executed, the custom error handler will not be used because the custom program has not been registered at that time.

The test code is as follows:

/**
 *
 * @param type $error_level 错误级别
 * @param type $error_message    错误信息
 * @param type $error_file 可选 错误文件
 * @param type $error_line 可选 错误行
 * @param type $error_context 可选。规定一个数组,包含了当错误发生时在用的每个变量以及它们的值。
 */
function my_error($error_level, $error_message, $error_file, $error_line, $error_context) {
  echo date('Y-m-d H:i:s') . $error_level . $error_message . $error_file . $error_line;
  var_dump($error_context);
}
set_error_handler('my_error', E_ALL);
print_r($a);
 

//From the above case, we can know that when registering the my_error method, the system will automatically overwrite the original error handling error_fuction() method
The result of running the above program:

Custom error trigger

Definition and usage

The trigger_error() function creates a user-defined error message.

trigger_error() is used to trigger an error message under user-specified conditions. It is used with the built-in error handler or with user-defined functions created with the set_error_handler() function.

If an illegal error type is specified, this function returns false, otherwise it returns true.

Grammar

trigger_error(error_message,error_types)

Parameters

Description

error_message

Required. Specifies the error message. Length limit is 1024 characters.

error_types

可选。规定错误消息的错误类型。 可能的值:

  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE
测试代码如下:
/**
 *
 * @param type $level
 * @param type $msg
 */
function my_error($level, $msg) {
  switch ($level) {
  case E_USER_ERROR:
    echo "ERROR:<br/>";
    break;
  case E_USER_WARNING:
    echo "WARNING:<br/>";
    break;
  case E_USER_NOTICE:
    echo "NOTICE:<br/>";
    break;
  default:
    break;
  }
  echo "错误编号:" . $level . " <br/>";
  echo "错误信息:" . $msg;
}
//注册错误处理器
set_error_handler('my_error');
if (89 > 8) {
  //调用错误触发器
  trigger_error('这是错误啊', E_USER_WARNING);
}

运行结果如下:

WARNING:
错误编号:512
错误信息:这是错误啊

以上所述就是本文的全部内容了,希望大家能够喜欢。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1027497.htmlTechArticlePHP 错误处理机制,php处理机制 在日常的项目开发过程中,总是会出现一些我们意想不到的异常错误,如果我们对此没有进行相对完善的处...
Statement
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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!