Errors and exceptions encountered by PHP programmers Part 1 Errors

不言
Release: 2023-03-23 11:48:02
Original
2088 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template