


Errors and exceptions encountered by PHP programmers Part 1 Errors
The content of this article is about the errors and exceptions encountered by PHP programmers. Now I share it with you. Friends in need can refer to it
1. Introduction to the error module in PHP
PHP errors and exceptions are two different concepts
1.1 Error type
Syntactic errors, such as missing semicolons
Environmental errors, such as permissions, failure to open files, and database server unavailability
Logical errors, such as a==b written as a=b
1.2 PHP common error levels
#Depracated
The lowest level error (deprecated is not recommended, not recommended, such as the old version of regular expressionsereg()
The function can be replaced and it will not affect the execution of PHP)Notice
Notification level error (caused by improper syntax, not Affect the normal operation of PHP, such as printing an undefined variable, so we must develop good writing practices from the beginning)Warning
Warning level errors (The code must be modified)Fatal error
Fatal level error,the program will stop
Parse error
Syntax parsing error, check before running the code,will not be able to execute the code
##E_USER_related errors
Errors defined by the user, used when manually throwing errors
error_reporting=E_ALL & ~E_NOTICE # 显示所有但不显示提醒错误
display_errors = Off|On # 是否显示错误,线上后关闭提高用户体验
Copy after login
1.3.2 Dynamic settingserror_reporting=E_ALL & ~E_NOTICE # 显示所有但不显示提醒错误 display_errors = Off|On # 是否显示错误,线上后关闭提高用户体验
error_reporting() # 专业php错误处理设置函数,动态设置错误级别
error_reporting(0) # 不显示所有错误,但是解析parse语法错误会显示
error_reporting(-1) # 显示所有错误
Error_reporting(E_ALL|~E_WARING) # 除了警告错误以外的错误级别都报告
Copy after login
1.3.3 Set the value of configuration options at runtimeerror_reporting() # 专业php错误处理设置函数,动态设置错误级别 error_reporting(0) # 不显示所有错误,但是解析parse语法错误会显示 error_reporting(-1) # 显示所有错误 Error_reporting(E_ALL|~E_WARING) # 除了警告错误以外的错误级别都报告
ini_set(option,value)
ini_set(error_reporting,0)
ini_set(error_reporting,-1)
ini_set(error_reporting,E_ALL)
ini_set(display_errors,0)
ini_set(display_errors,OFF/0)
error_reporting(-1);
Copy after login
14. trigger_error is triggered manually Wrong transmission of ini_set(option,value) ini_set(error_reporting,0) ini_set(error_reporting,-1) ini_set(error_reporting,E_ALL) ini_set(display_errors,0) ini_set(display_errors,OFF/0) error_reporting(-1);
@ Error suppressor, placed at the beginning of the line does not display the error of the line
trigger_error('Error prompt Content',E_USER_NOTICE)
E_USER_NOTICE # 继续执行(通知级别)
E_USER_WARNING # 继续执行(警告错误)
E_USER_ERROR # 程序不再执行(致命错误)
2.1 Save the error log in the specified file
ini_set('display_errors','off') # 不显示错误给用户 ini_set("error_log","c:\error.log"); error_reporting(-1); # 显示所有错误
2.2 Save the error log in the system log
ini_set("error_log", 'syslog')
2.3 Send the error log to the email
error_log("this is a errormsg",1,xxxxx@qq.com);
3. Custom Error Handler
3.1 set_error_handler Custom Error Handler
set_error_handler("自定义函数名",'错误级别(选填)') # 设置一个用户定义的错误处理函数 restore_error_handler(); # 回收(取消自定义错误函数接管php系统错误)
##3.2 Custom Error Handler
class MyErrorHandler{ //错误信息 public $message = ''; //错误文件 public $filename = ''; //错误行号 public $line = 0; //额外信息 public $vars = array(); protected $_noticelog = 'G:\notice\noticeLog.log'; public function __construct($message, $filename, $line, $vars) { $this->message = $message; $this->filename = $filename; $this->line = $line; $this->vars = $vars; } //根据不同错误级别对应不同操作 //遵循handler错误处理原则,errno:错误代码,line:错误行号 public static function deal($errno,$errmsg,$filename,$line,$vars) { $self = new self($errmsg,$filename,$line,$vars); switch ($errno) { case E_USER_ERROR://致命级别 return $self->dealError(); break; case E_USER_WARNING://警告级别 case E_WARNING: return $self->dealWarning(); break; case E_NOTICE://通知级别 case E_USER_NOTICE: return $self->dealNotice(); break; default: return false; } } /** * 如何处理致命错误 */ public function dealError() { //开启内存缓冲 ob_start(); //回溯上一条信息 debug_print_backtrace(); $backtrace = ob_get_flush(); $errorMsg = <<<EOF 出现了致命错误,如下: 产生错误的文件:{$this->filename} 产生错误的信息:{$this->message} 产生错误的行号:{$this->line} 追踪信息:{$backtrace} EOF; // error_log($errorMsg,1,'xxxx@qq.com'); error_log($errorMsg,3,$this->_noticelog); exit(1); } /** * 如何处理警告错误 */ public function dealWarning() { $errorMsg = <<<EOF 出现了警告错误,如下: 产生警告的文件:{$this->filename} 产生警告的信息:{$this->message} 产生警告的行号:{$this->line} EOF; // return error_log($errorMsg,1,'xxx@qq.com'); return error_log($errorMsg,3,$this->_noticelog); } /** * 如何处理通知错误 */ public function dealNotice() { $datetime = date('Y-m-d H:i:s',time()); $errorMsg = <<<EOF 出现了通知错误,如下: 产生通知的文件:{$this->filename} 产生通知的信息:{$this->message} 产生通知的行号:{$this->line} 产生通知的时间:{$datetime} EOF; return error_log($errorMsg,3,$this->_noticelog); } }
require_once 'MyErrorHandler.php';
error_reporting(-1);
//使用MyErrorHandler类直接调用deal方法
/**
* set_error_handler(array(类名/new 类名,方法名));
* set_error_handler(函数名);
*/
set_error_handler(array('MyErrorHandler','deal'));
//通知级别错误
echo $test;
//警告级别错误
settype($var,'king');
//致命错误
//test();
//总结:手动抛出的信息会被显示在浏览器
trigger_error('我是手动抛出的致命错误',E_USER_ERROR);
echo 'this is a test ';
Copy after login
3.4 Register_shutdown_function function usage require_once 'MyErrorHandler.php'; error_reporting(-1); //使用MyErrorHandler类直接调用deal方法 /** * set_error_handler(array(类名/new 类名,方法名)); * set_error_handler(函数名); */ set_error_handler(array('MyErrorHandler','deal')); //通知级别错误 echo $test; //警告级别错误 settype($var,'king'); //致命错误 //test(); //总结:手动抛出的信息会被显示在浏览器 trigger_error('我是手动抛出的致命错误',E_USER_ERROR); echo 'this is a test ';
Usage scenarios:
The page was forced to stop
The program code unexpectedly terminated or timed out
## register_shutdown_function()The function is
from memory, that is, after the PHP statement is executed (The page no longer exists) Call this function again, so when writing the path, you have already separated from the script, so
file_put_contents()The path must use an absolute path
error_get_last # 得到最后产生的错误
Note:
If there is die/exit before
register_shutdown_function(), it will not be executed不finished! To be continued in the next article:
Errors and exceptions encountered by PHPer in those years: Exceptions in the next article
Reference course video: Errors and exceptions you encountered in those years abnormal
The above is the detailed content of Errors and exceptions encountered by PHP programmers Part 1 Errors. 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

AI Hentai Generator
Generate AI Hentai for free.

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

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

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

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

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

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.
