One. PHP error and exception handling (i)

Source: Internet
Author: User
Tags bitwise operators first string openlog php error syslog

1. Classification of errors
    1. Syntax error
      • program does not run, directly displays syntax errors (easiest to fix)
    2. Run-time error
      • An error occurs only if the program runs to a row, or if it is run in a specific situation
    3. Logic error
      • The program does not run from start to finish (and prompts) the error, but the result of the program run calculation is wrong

The main thing we programmers face and the error to deal with is a run-time error.

2. Error Reporting level
Level Constants Error Report Description corresponding integer value
E_error Fatal Run-time error (it prevents execution of the script) 1
E_warning Run-time warning (non-fatal error) 2
E_parse Parsing errors from the syntax 4
E_notice Runtime Note message (may or may not be a problem) 8
E_core_error Similar to E_error, but does not include errors caused by PHP core 16
E_compile_error Fatal compile-time error 64
E_compile_warning Fatal compile-time warning 128
E_user_error User-induced error messages 256
E_user_warning User-induced warnings 512
E_user_notice User-induced Note message 1024
E_all All errors, warnings and notices 2047
E_strict Compatibility and interoperability recommendations for PHP version porting

If you want to display an error message, you need to set display_errors on in php.ini to turn on the PHP output error reporting feature.

;http://php.net/display-errorsdisplay_errors = on

You can also call the Ini_set () function in a PHP script to dynamically set a directive in the configuration file php.ini.

<?phpini_set(‘display_errors‘,true);
3. Adjust the error reporting level
    1. By setting php.ini, modify the value of error_reporting, and restart the Web server after the modification succeeds. Bitwise operators can be [& (and), | ( OR), ~ (non)] and error levels used together
;可以抛出任何非注意的错误,默认值error_reporting = E_ALL&~E_NOTICE;只考虑致命的运行时错误,解析错误和核心错误;error_reporting = E_ERROR|E_PARSE|E_CORE_ERROR;报告除了用户导致的错误之外的所有错误;error_reporting = E_ALL&~(E_USER_ERROR|E_USER_WARNING|E_USER_NOTICE)

Explain it, read the previous blog post.

E_NOTICE:       0000000000001000E_WARNING       0000000000000010E_USER_ERROR:  0000000100000000或运算(|)       00000001 00001010| E_STRICT;它是这样的结果:E_ALL           0111011111111111E_STRICT:       0000100000000000或运算(|)       01111111 11111111
    • You can use error_reporting() functions to adjust this behavior based on each script
<?phperror_reporting(0);//设置为0会完全关闭错误报告error_reporting(E_ALL);//将会向PHP报告发生的每个错误error_reporting(E_ALL&~E_NOTICE);//可以抛出任何非注意的错误报告
    • Use ini_set() Direct settings
<?phpini_set(“error_reporting”,  E_NOTICE);    //只显示E_NOTICE错误ini_set(“error_reporting”,  E_NOTICE | E_WARNING);  ////显示E_NOTICE和E_WARNING错误ini_set(“error_reporting”,  E_ALL | E_STRICT & ~E_NOTICE);    //只关闭E_NOTICE错误ini_set();//含义可以设定几乎所有php.ini中的设定项,形式如下:ini_set(“设定项名称” ,值);//这种设定都只对当前脚本有效,而且无需重启apache,很方便。//另一个对应函数是:ini_get(“设定项名称”);//用于获取某项的值。
4. Use the Trigger_error () function to replace die ()

The function die () is equivalent to exit() both if execution aborts the PHP program, and Trigger_error () can generate a user warning instead. For example, trigger_error("没有找到文件",E_USER_ERROR) using the Trigger_error () function instead of die (), the code will have an advantage in handling errors.

5. Custom error Handling

There are several scenarios where you can consider custom error handling.

    • You can write down the error message. Find some problems in production environment in time
    • can be used to mask errors. Prevent information from leaking to users, most likely to be hacked
    • You can do the appropriate processing by putting all the error reports into the final output of the script. Or error can show jump to a predefined error page, provide a higher user experience, if necessary, you can also in the custom error handler, according to the situation to terminate the script run
    • Can be used as a debugging tool,

Typically, set_error_handler() a function is used to set a user-defined error-handling function that creates an error-handling method of its own definition at runtime, returns an old error handler, and returns null if it fails.

The function has two parameters, where the first parameter is required and a callback function is required to specify the function to run when an error occurs. This callback function must declare 4 parameters, otherwise invalid, in order for the presence of errors, error messages, error files and error line numbers. The set_error_handler() second parameter of the function is optional, which specifies the error report level at which the user-defined error is displayed. The default is "E_all". For example:

<?phpError_reporting (0);//bug in the Shield program function error_handler($error _level, $error _message, $file, $line) {    $exit=FALSE;Switch($error _level) {//Alert level         CaseE_notice: CaseE_user_notice;$error _type=' Notice '; Break;//Warning level         Casee_warning; Casee_user_warning;$error _type=' Warning '; Break;//Error level         CaseE_error; CaseE_user_error;$error _type=' Fatal Error ';$EXIT=TRUE; Break;default:$error _type=' Unknown '; Break; }//Direct printing error message, can also be written as a file, write the databaseprintf"<font color= ' #FF0000 ' ><b>%s</b></font>:%s in <b>%s</b> on line <b>%d </b><br>\n ",$error _type);//If the error affects the normal execution of the program, jump to the friendly error prompt page    if(TRUE==$EXIT){Echo ' <script>location= ' err.html ';</script> '; }}//This is the real key point, handing the wrong treatment to Error_Handler ();Set_error_handler (' Error_Handler ');//Use of undefined variables will be reported noticeEcho $novar;//divided by 0 will report a warningEcho 3/0;//Customize an errorTrigger_error (' Trigger a fatal error '. E_USER_ERROR);Echo "DDDDD";

The system directly reported fatal error is not captured here, because the system can not give you such a big mistake to deal with

Attention:

    1. E_ERROR,E_PARSE,E_CORE_ERROR,E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNINGWill not be handled by this handle, that is, will be displayed in the most primitive way, but these errors are compiled or PHP kernel error, in general, will not occur.

      • After use, it will be set_error_handler() error_reporting() invalidated. That is, all errors (except those mentioned above) will be given to the custom function processing
6. Write error log

In the development phase, we usually show all errors--intent to resolve the error
In the product phase, we usually hide all errors-and simultaneously log error messages to a file-the error log file.

6.1 Logging error report logs using specified files

If you log error logs using the files you specify, be sure to keep this file out of the document root directory to reduce the likelihood of being attacked. And the file must have write permissions for the executing user (Web server process owner) of the PHP script.

error_reporting = E_ALL ;将会项PHP报告发生的每个错误display_errors = off ;不显示满足上条指令所定义规则的所有错误报告log_errors = On ;决定日志语句记录的设置log_errors_max_len = 1024   ;设置每个日志项的最大长度error_log = /usr/local/error.log   ;指定产生的错误报告写入的日志位置;此时,该文件没有给定路径,则系统会在每个文件夹下建立该文件并记录进去。

Using error_log() a function in PHP, a user-defined error message is sent, and the prototype of the function is as follows:

bool error_log(string message [,int message_type [,string destination [,string extra_headers]]])

This function sends an error message to the Web server's error log file, a TCP server, or to the specified file. Returns True if the function executes successfully, or false if it fails.

    1. The first parameter, message, is a required option, which is the error message to send. If you use this parameter only, the message is sent by the location set in php.ini in the configuration file.
      • The second parameter message_type is an integer value: 0 is sent to the operating system's log, 1 uses the PHP mail () function, sends the message to an e-mail, the fourth parameter extra_headers is also used, and 2 sends the error message to the TCP server. At this point the third parameter, destination, indicates that the destination IP and port;3 the information to the file destination.
<?phperror_log("出麻烦了",0);    //写入操作系统日志中error_log("出现麻烦了",1,"[email protected]");    //发送到管理员邮箱中error_log("搞砸了"2"localhost:5000");  //发送到本机对应5000端口的服务器中error_log("搞砸了"3"/usr/local/errors.log");
6.2 Error messages logged into the operating system log

Error reports can also be recorded in the operating system log, the Linux system error statements will be sent to Syslog, and in Windows error will be sent to the event log.

error_reporting = E_ALL ;将会项PHP报告发生的每个错误display_errors = off ;不显示满足上条指令所定义规则的所有错误报告log_errors = On ;决定日志语句记录的设置log_errors_max_len = 1024   ;设置每个日志项的最大长度error_log = syslog   ;指定产生的错误报告写入的操作系统的日志

PHP allows a custom message to be sent to syslog in the system. PHP provides 4 specialized functions that need to be used together.

    1. Define_syslog_variables () a function that must be called before using the Openlog (), syslog (), and Closelog () functions. It initializes some of the necessary constants.
    2. Openlog () Opens a connection to the logger in the current system, prepares for inserting log messages into the system, and inserts the first string argument supplied into each log message, which also requires specifying two parameters that will be used in the log context, which can be referenced in the official documentation.
    3. Syslog () 该函数向系统日志中发送一个定制消息。必选两个参数,1.通过指定一个常量定制消息的优先级。例如 log_warning 表示一般的警告, Log_emerg ' indicates a serious problem that predicts the system to crash. The second parameter is to send a custom message to the system log, to provide a message string, or to be an error string at run time for the PHP engine
    4. Closelog () closes the log connection.

If Syslog is already turned on, for example:

<?phpdefine_syslog_variables();openlog("PHP5",LOG_PID, LOG_USER);syslog(LOG_WARNING,"警告报告向syslog发送的演示,警告时间:".date("Y/m/d H:i:s"));closelog();

One. PHP error and exception handling (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.