PHP custom error processor processing error information

Source: Internet
Author: User

If you are a veteran of PHP, you certainly know what happens when a PHP script error occurs. In this case, the PHP parser will provide an error message on the screen, as shown in figureFatal error: Call to undefined function on line 19 --, So the program is terminated here. This information will scare the customer, and he may immediately call you for consultation.

Fortunately, there is a solution here. PHP has built-in tools that allow developers to capture script errors and then transfer them to custom error processors. In this case, you can program the processor to display more error details. You can also write errors to files or databases to take remedial measures. Sometimes you can write programs on the processor to ignore error messages.

In this article, I will explain how to use the PHP error processing API to build a custom error processor, and how to display and manage script error messages in a simple and friendly way.

Error Type and report level

We start from the most basic. PHP has three basic error types, from low-level to advanced: Attention, warning, and error (or fatal error ). In general, attention and warning will not terminate the program, but a fatal error is a dangerous fault (for example, calling an undefined function or referring to a non-existent object), which will lead to program interruption. These errors may occur during startup, parsing, compilation, or running.

Keywords suchE_notice, e_errorIs used to indicate different types and levels of errors. You can obtain a list of their details in the PHP manual.

Script stage error displayError_reporting ()Function. This function sets different parameters for different error levels.TableAScript programs that report warnings and fatal errors using this function are provided.

Table
<? PHP
// Display warnings and errors
Error_reporting (e_warning | e_error );
// This will generate a notice, which will never be displayed
Echo $ undefinedvar;
// This will generate a fatal error, which will be displayed
Callundeffunc ();
?>

SetTableBCompared with the above Code,Listing BSo that the error information is not displayed.

Table B

<? PHP
// Turn off error display
// No errors will be displayed
Error_reporting (0 );
// This will generate a notice
Echo $ undefinedvar;
// This will generate a fatal error
Callundeffunc ();
?>

The code in Table C shows all error messages and even simple precautions:

Table C

<? PHP
// All errors will be displayed
Error_reporting (e_all );
// This will generate a notice
Echo $ undefinedvar;
// This will generate a fatal error
Callundeffunc ();
?>

As shown in the preceding three examples,Error_reporting ()When a function control error occurs, it is very important to display the content on the screen. The keyword here isDisplayed, Which means the error is not displayed, rather than the error is not. Therefore, when a fatal error occurs (for example, an incorrect function call), the program is terminated. However, no message is displayed to the user.

The following example (TableD) Describes the situation:

Table D
<? PHP
// No errors will be displayed
Error_reporting (0 );
// Start a task
Echo "Starting task ...";
// Call an undefined Function
// A fatal error occurs during Task Processing
Callme ();
// End the task
Echo "successfully completed task ...";
?>

InTableDInEcho ()A fatal error occurs in the function. When the program is executed, it is terminated, but no error message is provided. The user does not know that the program is running correctly. The conclusion below is very obvious: it is very dangerous not to give an error report because incorrect conclusions are often caused regardless of whether the process is completed or not.

Note:Calls without any parametersError_reporting ()The current error report level is returned.

Custom error Processor

Obviously, hiding error reports is incorrect. You must be wondering what other methods to improve them. The custom error processor is a good solution to replace the default PHP error handling system. The custom error processor can process error messages in any way, including how information is displayed.

In PHP functionsSet_error_handler ()Function. When an error occurs, this function is automatically called and four parameters are provided: Error code, error message, error Script Name, and error row. This function is responsible for error management.

TableEA simple example is provided:

Table E

<? PHP
// Define Custom Handler
Set_error_handler ('myhandler ');
// Custom Handler code
Function myhandler ($ code, $ MSG, $ file, $ line ){
Echo "just so you know, something went wrong at line $ line of your script $ file. the system says that the error code was $ code, and the reason for the error was: $ MSG. sorry about this! ";
}
// Generate a notice
Echo $ undefvar;
?>

When running this script, the following information appears:

Just so you know, something went wrong at line 11 of your/dev/error1.php. the system says that the error code was 8, and the reason for the error was: undefined variable: undefvar. sorry about this!

In this case, the default PHP error processor is defined by the user.Myhandler ()Function replaced,$ UndefvarWhen the variable is activated, PHP notifies the undefined variable information, which is generated by the runtime engine and then passedMyhandler ()Function, and the address of the error is also passed to this function. ThenMyhandler ()An error occurred while interpreting function output friendly information.

Note:: Errors and fatal errors are important. They bypass the custom error processor andPHPThe default error handling mechanism is displayed. Display this information using the standards discussed earlierError_reporting ()Function.

Example 1: dynamic error page and email alarm

TableFAnother example is provided. When an error occurs, an HTML error page is generated dynamically and reported to the Web Administrator via e-mail.

Table F

<? PHP
// Define Custom Handler
Set_error_handler ('myhandler ');
// Custom Handler code
Function myhandler ($ code, $ MSG, $ file, $ line,$ Context){
// Print error page
Echo "<HTML> Echo "<H2 align = center> error! </H2> ";
Echo "<font color = Red size = + 1> ";
Echo "An error occurred while processing your request. Please visit our <a href = http://www.domain.dom> Home page </a> and try again .";
Echo "</font> ";
Echo "</body> // Email error to Admin
$ Body = "$ MSG at $ file ($ line), timed at". date ("D-M-Y H: I: s", mktime ());
$ Body. = "Nn". print_r ($ context, true );
Mail ("webmaster@domain.dom", "web site error", $ body );
// Halt execution of script
Die ();
}
// Generate a notice
Echo $ undefvar;
?>

Here, custom error processors dynamically generate HTML error pages when an error occurs. This error message can also be captured by the e-mail information, and then the built-in PHPMail ()The function is sent to the Administrator.

Here, a new parameter $ context of the myhandler () function is displayed. This is the fifth parameter of the myhandler () function and is optional. It contains a snapshot of the current variable status. Including contextual information useful to administrators, which helps reduce debugging time.

Example 2: custom error logs

TableGAnother example is provided to illustrate how the custom error processor inputs detailed error information into the file.

Table G
<? PHP
// Define Custom Handler
Set_error_handler ('myhandler ');
// Custom Handler code
Function myhandler ($ code, $ MSG, $ file, $ line ){
// Print error page
Echo "<HTML> Echo "<H2 align = center> error! </H2> ";
Echo "<font color = Red size = + 1> ";
Echo "An error occurred while processing your request. Please visit our <a href = http://www.domain.dom> Home page </a> and try again .";
Echo "</font> ";
Echo "</body> // Log error to file, with context
$ Logdata = date ("D-M-Y H: I: s", mktime (). ", $ code, $ MSG, $ line, $ filen ";
File_put_contents ("Web. log", $ logdata, file_append );
// Halt execution of script
Die ();
}
// Generate a warning
Echo is_float ();
?>

Similar to the previous example, it also generates an error page and inputs the error data to a file for the Administrator to view it. Data is stored in CSV format and has simple data analysis and reports. Note that in this example and the previous example, the error code is called at the end of the error handling code.Die ()To make sure that the script is no longer running.

As shown in the preceding example, the custom error processor allows you to handle PHP script errors in a friendly way. You can make full use of your creativity, but remember that any increase in flexibility is accompanied by an increase in overhead and time.

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.