When writing php programs, error handling is an important part. If the program lacks the error detection code, it looks unprofessional and opens the door for security risks. for example:
The code is as follows:
$ A = fopen('test.txt ', 'r ');
// The file is opened without judgment. if the file does not exist, an error is returned.
?>
The correct statement should be as follows:
The code is as follows:
If(file_exists('test.txt ')){
Using fw.fopen('test.txt ', 'r ');
// Close after use
Fclose ($ f );
}
?>
I. PHP error handling methods A. simple die () statements;
Equivalent to exit ();
Example:
The code is as follows:
If (! File_exists('aa.txt ')){
Die ('file does not exist ');
} Else {
// Perform the operation
}
// If the die () is triggered, the echo is not executed here.
Echo 'OK ';
Concise syntax:
The code is as follows:
File_exits('aaa.txt ') or die ('file does not exist ');
Echo 'OK ';
B. Custom errors and error triggers
1. Error Processor (custom error, usually used for syntax error handling)
Create a custom error function (processor). This function must be able to process at least two parameters (error_level and errormessage), but can accept up to five parameters (error_file, error_line, error_context)
Syntax:
The code is as follows:
Function error_function ($ error_level, $ error_message, $ error_file, $ error_line, $ error_context)
// After creation, you need to rewrite set_error_handler (); function
Set_error_handler ('error _ function', E_WARNING); // Here, error_function corresponds to the custom processor name created above, and the second parameter is the error level of the Custom error Processor;
Error Report level (learn more)
These error reporting levels are different types of errors that the error handler aims to handle:
Value |
Constant |
Description |
2 |
E_WARNING |
Non-fatal run-time error. Do not pause script execution. |
8 |
E_NOTICE |
Run-time notification. An error may occur when the script runs normally. |
256 |
E_USER_ERROR |
Fatal user-generated error. This is similar to the E_ERROR set by the programmer using the PHP function trigger_error. |
512 |
E_USER_WARNING |
Non-fatal user-generated warning. This is similar to the E_WARNING set by the programmer using the PHP function trigger_error. |
1024 |
E_USER_NOTICE |
User-generated notifications. This is similar to the E_NOTICE set by the programmer using the PHP function trigger_error. |
4096 |
E_RECOVERABLE_ERROR |
Possible fatal errors. Similar to E_ERROR, but can be captured by a user-defined handler. (See set_error_handler ()) |
8191 |
E_ALL |
All errors and warnings except level E_STRICT. (In PHP 6.0, E_STRICT is part of E_ALL) |
2. error triggers (generally used to handle logical errors)
Requirement: for example, to receive an age, if the number is greater than 120, it is considered an error.
Traditional method:
The code is as follows:
'If ($ age> 120 ){
Echo 'age error'; exit ();
}
Trigger:
The code is as follows:
'If ($ age> 120 ){
// Trigger_error ('error information' [, 'error level']); the error level is optional and is used to define the error level.
// User-defined levels include E_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE.
Trigger_error ('Age error'); // The default error handling method of the called System. you can also use a custom processor.
}
// Custom processor, same as above
Function myerror ($ error_level, $ error_message ){
Echo 'error text ';
}
// At the same time, you need to change the default processing function of the system.
Set_error_handler ('myerror', E_USER_WARNING); // same as above, the first parameter is the name of the custom function, and the second parameter is the error level. the error level here is generally the following: e_USER_WARNING, E_USER_ERROR, and E_USER_NOTICE]
// Now trigger_error can be used to customize the error handling function.
Exercise questions:
The code is as follows:
Date_default_timezone_set ('prc ');
Function myerror ($ error_level, $ error_message ){
$ Info = "error code: $ error_level \ n ";
$ Info. = "error message: $ error_message \ n ";
$ Info. = 'Occurrence Time: '. date ('Y-m-d H: I: s ');
Using filename='aa.txt ';
If (! $ Fp = fopen ($ filename, 'A ')){
'File creation '. $ filename. 'failed ';
}
If (is_writeable ($ filename )){
If (! Fwrite ($ fp, $ info )){
Echo 'failed to write the file ';
} Else {
Echo 'error message recorded successfully ';
}
Fclose ($ fp );
} Else {
Echo 'file'. $ filename. 'unwriteable ';
}
Exit ();
}
Set_error_handler ('myerror', E_WARNING );
Using fpw.fopen('aaa.txt ', 'r ');
?>
C. error log
By default, according to the error_log configuration in php. ini, php sends error records to the server's error record system or file. You can use the error_log () function to send error records to files or remote destinations;
Syntax:
Error_log (error [, type, destination, headers])
The type part usually uses 3 to indicate appending an error message to the end of the file, instead of overwriting the original content.
Destination indicates the destination, that is, the stored file or remote destination.
For example, error_log ("$ error_info", 3, "errors.txt ");
II. PHP exception handling [key]
1. Basic syntax
The code is as follows:
Try {
// Code that may contain errors or exceptions
// Catch Exception is an Exception class defined by php
} Catch (Exception $ e ){
// Handle the exception. method:
// 1. handle it by yourself
// 2. if it is not processed, throw it again
}
2. processing procedures should include:
Try-the abnormal function should be located in the "try" code block. If no exception is triggered, the code continues as usual. However, if an exception is triggered, an exception is thrown.
Throw-This specifies how to trigger an exception. Each "throw" must correspond to at least one "catch"
The Catch-"catch" code block captures exceptions and creates an object containing exception information.
Let's trigger an exception:
The code is as follows:
// Create a function that can throw an exception
Function checkNum ($ number ){
If ($ number> 1 ){
Throw new Exception ("Value must be 1 or below ");
}
Return true;
}
// Trigger an exception in the try code block
Try {
CheckNum (2 );
// If an exception is thrown, the following line of code will not be output
Echo 'If you see this, the number is 1 or below ';
} Catch (Exception $ e ){
// Capture exceptions
Echo 'message: '. $ e-> getMessage ();
}
?>
The above code will get an error similar to this:
Message: Value must be 1 or below
Example:
The above code throws an exception and captures it:
Create the checkNum () function. It checks whether the number is greater than 1. If yes, an exception is thrown.
Call the checkNum () function in the "try" code block.
An exception in the checkNum () function is thrown.
The "catch" code block receives the exception and creates an object ($ e) containing the exception information ).
Call $ e-> getMessage () from this exception object to output error messages from this exception.
However, to follow the "each throw must correspond to a catch" principle, you can set a top-level exception processor to handle missed errors.
The set_exception_handler () function can be used to set user-defined functions for handling all uncaptured exceptions.
The code is as follows:
// Set a top-level exception processor
Function myexception ($ e ){
Echo 'this is top exception ';
} // Modify the default exception processor
Set_exception_handler ("myexception ");
Try {
$ I = 5;
If ($ I <10 ){
Throw new exception ('$ I must greater than 10 ');
}
} Catch (Exception $ e ){
// Handle exceptions
Echo $ e-> getMessage ().'
';
// Continue to throw if the exception is not handled
Throw new exception ('errorinfo'); // you can use throw $ e to retain the original error message;
}
Create a custom exception class
The code is as follows:
Class customException extends Exception {
Public function errorMessage (){
// Error message $ errorMsg = 'Error on Line'. $ this-> getLine (). 'in'. $ this-> getFile ().':'. $ This-> getMessage ().'Is not a valid E-Mail address '; return $ errorMsg;
}
}
// Use
Try {
Throw new customException ('error message ');
} Catch (customException $ e ){
Echo $ e-> errorMsg ();
}
Multiple catch methods can be used to return error messages in different situations.
The code is as follows:
Try {
$ I = 5;
If ($ I> 0 ){
Throw new customException ('error message'); // use a custom exception class for processing
} If ($ I <-10 ){
Throw new exception ('error2 '); // use the default system exception
}
} Catch (customException $ e ){
Echo $ e-> getMessage ();
} Catch (Exception $ e1 ){
Echo $ e1-> getMessage ();
}
Abnormal rules
Code that requires exception handling should be placed in the try code block to capture potential exceptions. Each try or throw code block must have at least one catch code block. Multiple catch code blocks can capture different types of exceptions. You can throw a (re-thrown) exception again in the catch code block in the try code. In short: if an exception is thrown, it must be caught.