- Modify the error report level
- Write errors
- Abnormal processing implementation
- Customization
- Capture multiple anomaly
Error handling
definition
- error: The mistakes in the development process, the error caused by the user operation.
- Cause
- Syntax error: Development environment prompt, unpacking, the script cannot be run.
- Runtime error: The script cannot run correctly. For example, a double quotation marker string parses the variable.
- Logical error: Common logical operation errors, loop condition settings, etc..
Error report level
1, Wamp as the development environment, in the php.ini configuration file, there are two parameter settings:
- display_errors = on
Note: The PHP parser will output the function of the error report. If it is a product formally released, you need to set this value to OFF on the PHP server.
- error_reporting = E_ALL
Note: The PHP parser will output each error.
2, PHP error report level:
value | constant | description |
1 | E_ERROR | Fatal run-time errors. Errors that can not be recovered from. Execution of the script is halted |
2 | E_WARNING | Non-fatal run-time errors. Execution of the script is not halted |
4 | E_PARSE | Compile-time parse errors. Parse errors should only be generated by the parser |
8 | E_NOTICE | Run-time notices. The script found something that might be an error, but could also happen when running a script normally |
16 | E_CORE_ERROR | Fatal errors at PHP startup. This is like an E_ERROR in the PHP core |
32 | E_CORE_WARNING | Non-fatal errors at PHP startup. This is like an E_WARNING in the PHP core |
64 | E_COMPILE_ERROR | Fatal compile-time errors. This is like an E_ERROR generated by the Zend Scripting Engine |
128 | E_COMPILE_WARNING | Non-fatal compile-time errors. This is like an E_WARNING generated by the Zend Scripting Engine |
256 | E_USER_ERROR | Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error() |
512 | E_USER_WARNING | Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error() |
1024 | E_USER_NOTICE | User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error() |
2048 | E_STRICT | Run-time notices. PHP suggest changes to your code to help interoperability and compatibility of the code |
4096 | E_RECOVERABLE_ERROR | Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler()) |
8191 | E_ALL | All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0) |
3, open the error report
Processing in a php.ini file configuration, if you are not enough to server permissions, you can use the INI_SET () function setting:
E.g:
ini_set(‘display_errors’,1);
Adjustment error report level
1. Modify the value of the configuration instruction error_reporting in php.ini
Defaults:
error_reporting = E_ALL
Modification Example 1 (Binding Combination Operators &, |, ~): All Error Reports Outside the Message during Run
error_reporting = E_ALL&~E-NOTICE;
Modification Example 2: Consider runtime error, parsing errors, core errors
error_reporting = E_ERROR | E_PARSE | E_CORE_ERROR
2, use the error_reporting () function in the script
Sufficient permissions is not enough, or you need a personalized page error report to use this function.
Error_Reporting (0); // Fully turn off error report Error_Reporting (e_all); // Report any error Error_Reporting (E_ALL & ~ E_NOTICE); // Report Any error except
Example:
/ * Open the Display_ERRORS Directive in PHP.ini * / ini_set ( 'display_errors', 1); / * Set in this script through the ERROR_REPORTING () function, output all levels of error report * / error_reporting ( E_ALL );//error_reporting ( E_ALL &~(E_WARNING|E_NOTICE)); / * "Note (Notice) report does not block the execution of the script, and may not be a problem * / GetType ($ var); // The parameter variable provided when calling the function is not previously declared. / * "Warning" report indicates a problem, but does not block the execution of the script * / GetType (); // does not provide the necessary parameters when calling the function / * "Error" report, it will terminate the program, the script will not be executed down again * / GET_TYPE (); // Call a function that is not defined
Use the Trigger_Error () function instead of the DIE () function
DIE () is equivalent to exit (), will exit the program. Trigger_ERROR () can generate a user warning instead of exit.
Sample code:
// DIE ("The program runs!");trigger_error("there is a bugbugbug!",E_USER_WARNING); Echo "Here is a PHP file tail";
Custom error handling
1. Situation that needs to customize the error message
- Record error message
- Shield error message
- Error Unified Output Page Processing or Same Page Location Output Error Message
- debugging
2, how to customize the error handling
User Custom Error Processing Function: SET_ERROR_HANDLER ()
Grammar format:
mixed set_error_handler ( callable $error_handler [, int $error_types = E_ALL | E_STRICT ] )
Parameter Description:
error_handler:
Handler (int $ errno, string $ errstr [, string $ errfile [, int $ Errline [, array $ errcontext]] // four parameter meanings: error level, error message, error location, error location Row
error_types:
Error report level. Default E_ALL.
Sample code:
// Shield all error reportserror_reporting ( 0 );function error_handler($error_level, $error_message, $file, $line) { $EXIT = false; $error_type=''; switch ($error_level) { // Remind case E_NOTICE : case E_USER_NOTICE : $error_type = 'Notice'; break; //caveat case E_WARNING : case E_USER_WARNING : $error_type = 'Warning'; break; // error case E_ERROR : case E_USER_ERROR : $error_type = 'Fatal Error'; break; //unknown mistake default: $error_type = 'Unknown'; $EXIT=true; break; } // Print Error Message, you can customize the error format printf("%s,%s,%s,%d",$error_type,$error_message,$file,$line); if(true==$EXIT){ echo '<script>location="error.php";</script>'; }} set_error_handler('error_handler');//echo $novar;echo 3/0;
note:
1. SET_ERROR_HANDLER () does not process the following error reports: E_ERR0R, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_Compile_ERROR, E_Compile_Warning. Do not deal with the error message not to be displayed, it does not display in the user setting format.
2. In addition to the errors listed in Article 1, all errors are handed over to the user after using the set_error_handler () function.
Practice 1: Custom Error Processing
1, SET_ERROR_HANDLER () function usage
2, custom callback function
3. Error report format:
Write errors
After the PHP project is deployed, general Display_errors = OFF. The error message of the program daily operation is required, as a runway reference, how to deal with? There are two ways to record logs:
1. Use the specified file to record the error report log
PHP.ini configuration
error_reporting = E_ALL
display_errors = off
log_errors=on
log_errors_max_len = 1024
error_log = "d:/wamp/logs/php_error.log"
ERROR_LOG () function
// Write an operating system log (requires Error_Log = syslog in php.ini)error_log("error message",0); // Send to email (required mail server)error_log("error message",1,"[emailprotected]"); // Send a port of an IPerror_log("error message",2,"localhost:5000"); // Write into a path fileerror_log("error message",3,"er.log");
2, error message record to the operating system log
PHP.ini configuration
error_reporting = E_ALL
display_errors = off
log_errors=on
log_errors_max_len = 1024
error_log = syslog
Send a custom message to the system using Syslog
//php5.3 Start, the correlation function has been abolisheddefine_syslog_variables();……
Abnormal processing
definition
Exception: An exception or an event that occurs during the execution of the program, which interrupts the running of the normal instruction, and jumps to other program modules to continue.
Simple abnormal processing
1, grammar structure
try{ / / Need to capture an abnormal code block}catch (Exception $ex1){ // Treatment exception} finally { / / Always executed code}
2, sample code
try { $number = 100; $div = 0; if ($div == 0) { Throw new Exception ("The divisor cannot be 0"); } $result=$number/$div; Echo 'calculation results'. $ results;} catch ( Exception $e ) { Echo 'program is abnormal:'. $ e-> getMessage ();}finally { Echo '<br> Finally code is always executed;} Echo '<br> procedures continue to execute';
Customized exception handling class
1, built-in Exception class structure
class Exception { protected $ message = 'unknown exception'; // Abnormal information protected $ code = 0; // User Custom Abnormal Code Protected $ file; // Expeated file name Protected $ line; // Executive code line number function __construct($message = null, $code = 0); Final function getMessage (); // Returns an exception information Final function getcode (); // Return to abnormal code Final function getfile (); // Returns an exception file name Final function getLine (); // Returns an exception code line number Final function gettrace (); // backtrace () array Final function gettracesstring (); // GetTrace () information that has become string / * Overloaded method * / Function __toString (); // Outputable string}
2, custom abnormal processing classes
/ * Customized exception handling class * /class MyException extends Exception { // Rewind constructor public function __construct($message, $code = 0) { parent::__construct ( $message, $code ); } / * Rewind the parent class __tostring magic method * / public function __toString() { return __CLASS__ . ":[" . $this->code . "]:" . $this->message . "<br>"; } / * Custom unusual method * / public function customFunction() { Echo "The type of abnormality" in the custom method is handled <br> "; }} try { $ Error = 'Allows this error'; throw new MyException ( $error ); Echo 'has an exception, the code that is not executed .....';} catch ( MyException $e ) { Echo 'captures exception:'. $ E; $e->customFunction ();} Echo 'procedure continues ...';
Practice 2: Customization
Multi-way abnormal capture
class MyException extends Exception { public function __construct($message, $code = 0) { parent::__construct ( $message, $code ); } public function __toString() { return __CLASS__ . ":[" . $this->code . "]:" . $this->message . "<br>"; } public function customFunction() { Echo "The type of exception is handled according to the custom method"; }} class TestException { public $var; function __construct($value = 0) { switch ($value) { case 1 : Throw new myException ("Inferred value" 1 "is an invalid parameter", 5); break; case 2 : Throw New Exception ("Inferred value" 2 "does not allow as a parameter", 6); break; default : $this->var = $value; break; } }} // Example 1$testObj=null;try { $ testobj = new testException (); // Create an exception test class object using the default parameter echo "*********** <br>"; // No throwing an exception, this statement will be performed normally } catch (MyException $ E) {// Capture user-defined exception block Echo "Captures Customized Exceptions: $ E <BR>"; // Output Abnormal Messages by Customize $ E-> CustomFunction (); // You can call custom unusual processing methods } Catch (Exception $ E) {// Capture the object of exception handling class built into PHP Echo "captures the default exception:" $ E-> getMessage (). "<br>"; // Output exception message} VAR_DUMP ($ TESTOBJ); / / Judgment whether the object creates success, if there is no exception, create success // Example 2, throw a custom exception, and capture this exception and processed by custom exception processing classes$testObj1=null;try { $ TESTOBJ1 = New TestException (1); // When the parameter 1, create a test class object throw a custom exception echo "*********** <br>"; // This statement will not be executed } Catch (MyException $ E) {// The code in this CATCH block will be executed Echo "Captures Customized Exceptions: $ E <br>"; $e->customFunction (); } Catch (Exception $ E) {// This Catch block is not performed Echo "captures the default exception:" $ E-> getMessage (). "<br>";} VAR_DUMP ($ TESTOBJ1); // has an abnormality, this object is not created successfully // Example 2, throw the built-in exception, and capture this exception and processed by custom abnormal processing classes$testObj2=null;try { $ TESTOBJ2 = New TestException (2); // When the parameter 2, create a test class object throw a built-in exception echo "*********** <br>"; // This statement will not be executed } catch (myException $ e) {// This Catch block is not performed Echo "Captures Customized Exceptions: $ E <br>"; $e->customFunction (); } Catch (Exception $ E) {// The code in this CATCH block will be executed Echo "captures the default exception:" $ E-> getMessage (). "<br>";} Var_dump ($ TESTOBJ2); // has an abnormality, this object is not created successfully