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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles