search
HomeBackend DevelopmentPHP TutorialPHP error handling issues
PHP error handling issuesMar 26, 2017 am 09:18 AM

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:

  1. thrown manually by the user
    E_USER_NOTICE, E_USER_WARNING, E_USER_ERROR, E_USER_DEPRECATED

  2. User-caused
    E_NOTICE, E_PARSE, E_WARNING, E_ERROR, E_COMPILE_ERROR, E_COMPILE_WARNING, E_STRICT, E_RECOVERABLE_ERROR


  3. 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

  1. Termination of program execution
    The program terminates and enters the error handling process

  2. Does 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

  1. error_reporting
    Reporting error type, it is recommended to configure E_ALL in the development/testing environment. After solving all types of errors, configure E_ALL in the production environment & E_DEPRECATED, indicates: report all errors except discarded errors

  2. ##display_errorsWhether to display errors, configure it to false in the production environment , combined with the settings of
    error_reporting above, it means: report all errors except discarded errors, but do not display error messages.

  3. ##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.

  4. 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 logger

Generally, 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:
Report all errors except discard errors, do not display error information, but record it to the

file_dirlog. The above configurations affect the most basic performance of php errors. Of course, these configurations can be changed in the code through

ini_set()

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.

As mentioned above, after an error occurs, an error handling process will be carried out. How is the error process defined?

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 flow

How 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!

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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),