Table of Contents
1. Introduction to the error module in PHP
1.1 Error type
1.2 PHP common error levels
2.1 Save the error log in the specified file
2.2 Save the error log in the system log
2.3 Send the error log to the email
3. Custom Error Handler
3.1 set_error_handler Custom Error Handler
       
Home Backend Development PHP Tutorial Errors and exceptions encountered by PHP programmers Part 1 Errors

Errors and exceptions encountered by PHP programmers Part 1 Errors

Apr 09, 2018 pm 03:44 PM
php programmer

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

  1. Syntactic errors, such as missing semicolons

  2. Environmental errors, such as permissions, failure to open files, and database server unavailability

  3. Logical errors, such as a==b written as a=b

1.2 PHP common error levels

  1. #DepracatedThe lowest level error (deprecated is not recommended, not recommended, such as the old version of regular expressions ereg()The function can be replaced and it will not affect the execution of PHP)

  2. NoticeNotification 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)

  3. Warning Warning level errors (The code must be modified)

  4. Fatal errorFatal level error, the program will stop

  5. Parse errorSyntax parsing error, check before running the code, will not be able to execute the code

  6. ##E_USER_related errors Errors defined by the user, used when manually throwing errors

1.3 How to set the error level

1.3.1 php.ini configuration file

error_reporting=E_ALL & ~E_NOTICE # 显示所有但不显示提醒错误
display_errors = Off|On # 是否显示错误,线上后关闭提高用户体验
Copy after login

1.3.2 Dynamic settings

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 runtime

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

@ Error suppressor, placed at the beginning of the line does not display the error of the line

Manually throw a custom error message:

trigger_error('Error prompt Content',E_USER_NOTICE)

Errors and exceptions encountered by PHP programmers Part 1 Errors

Error level:

E_USER_NOTICE # 继续执行(通知级别)
E_USER_WARNING # 继续执行(警告错误)
E_USER_ERROR # 程序不再执行(致命错误)
Copy after login
2. Processing in PHP 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); # 显示所有错误
Copy after login

2.2 Save the error log in the system log

ini_set("error_log", 'syslog')
Copy after login

2.3 Send the error log to the email

error_log("this is a errormsg",1,xxxxx@qq.com);
Copy after login

3. Custom Error Handler

3.1 set_error_handler Custom Error Handler

set_error_handler("自定义函数名",'错误级别(选填)') # 设置一个用户定义的错误处理函数    

restore_error_handler(); # 回收(取消自定义错误函数接管php系统错误)
Copy after login

       

Errors and exceptions encountered by PHP programmers Part 1 Errors##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,&#39;xxxx@qq.com&#39;);
        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,&#39;xxx@qq.com&#39;);
        return error_log($errorMsg,3,$this->_noticelog);
    }

    /**
     * 如何处理通知错误
     */
    public function dealNotice()
    {
        $datetime = date(&#39;Y-m-d H:i:s&#39;,time());
        $errorMsg = <<<EOF
        出现了通知错误,如下:
产生通知的文件:{$this->filename}
产生通知的信息:{$this->message}
产生通知的行号:{$this->line}
产生通知的时间:{$datetime}
EOF;
        return error_log($errorMsg,3,$this->_noticelog);
    }
}
Copy after login

3.3 Error handler test

require_once &#39;MyErrorHandler.php&#39;;
error_reporting(-1);
//使用MyErrorHandler类直接调用deal方法
/**
 * set_error_handler(array(类名/new 类名,方法名));
 * set_error_handler(函数名);
 */
set_error_handler(array(&#39;MyErrorHandler&#39;,&#39;deal&#39;));

//通知级别错误
echo $test;
//警告级别错误
settype($var,&#39;king&#39;);
//致命错误
//test();

//总结:手动抛出的信息会被显示在浏览器
trigger_error(&#39;我是手动抛出的致命错误&#39;,E_USER_ERROR);

echo &#39;this is a test &#39;;
Copy after login

3.4 Register_shutdown_function function usage

                   

          Errors and exceptions encountered by PHP programmers Part 1 ErrorsUsage scenarios:

The page was forced to stop

  1. The program code unexpectedly terminated or timed out

  2.  ​

## ​ register_shutdown_function()Errors and exceptions encountered by PHP programmers Part 1 ErrorsThe function is

called

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 # 得到最后产生的错误
Copy after login
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!

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

See all articles