Using PHP to customize error handlers to handle error messages

Source: Internet
Author: User
Tags date define error code error handling execution log php script variable
If you're a veteran of PHP, you know what happens when a php script goes wrong. The PHP parser then gives the error message on the screen, such as Fatal error:call to undefined function in line 19--so the program terminates here. This information will scare the customer, he may immediately call and you to consult.

Fortunately, there is a solution. PHP has built-in tools that allow developers to catch script errors and then move them to a custom error handler. In this case, you can program the processor to show more details about the error. You can also write errors to a file or database to take remedial action. Sometimes you can also ignore error messages for processor writers.

In this article, I'll explain how to use the error handling API of PHP to build user-defined error handlers, and show you how to display and manage error messages for scripts in a simple and friendly way.

Error type and reporting level

We start with the basics. PHP has three basic types of errors, from low-level to advanced: attention, warnings, and errors (or fatal errors). Typically, note and warning do not terminate the program, but a fatal error is a dangerous failure (for example, calling an undefined function or referencing a nonexistent object) will cause the program to break. These errors may occur at startup, resolution, compilation, or runtime.

Keywords such as e_notice, e_error, etc. are used to indicate the different types and levels of errors. A detailed list of their details can be obtained from the PHP manual.

The script phase error display is controlled by the error_reporting () function. This function sets different parameters for different error levels. Table A provides a script that reports warnings and fatal errors using this function.

Table A

Display warnings and Errors

Error_reporting (e_warning e_error);

This would generate a notice, which would never be displayed

Echo $undefinedVar;

This would generate a fatal error, which would be displayed

Callundeffunc ();

?>

Comparing the code in table B with the above shows that the error message is hidden in Listing B, and even the fatal message is hidden, so that the error message is not displayed.

Table B

Turn off error display

No errors would be displayed

error_reporting (0);

This'll generate a notice

Echo $undefinedVar;

This would generate a fatal error

Callundeffunc ();

?>

The Code in Table C shows all the error messages and even simple considerations:

Table C

All errors would be displayed

Error_reporting (E_all);

This'll generate a notice

Echo $undefinedVar;

This would generate a fatal error

Callundeffunc ();

?>

As shown in the 3 examples above, the error_reporting () function is important to display content on the screen when it comes to controlling errors. The key word here is displayed, whose expression means that the error is not displayed, not the error. Therefore, when a fatal error occurs (for example, an incorrect function call), the program is terminated, but no messages are displayed to the user at this time.

The following example (table D) illustrates this situation:

Table D

No errors would 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 ...";

?>

In table D, a fatal error occurred while invoking the Echo () function, which was terminated when the program was executed, but no error message was given, and the user was unaware that the program was running correctly. The following conclusions are obvious: it is dangerous not to give error reporting because it often leads to incorrect conclusions whether or not the process is completed.

Note: calling error_reporting () without any arguments will return the current error reporting level.

Custom Error processor

Obviously, it's not true to hide the error report, and you want to know what other ways to improve it. Custom error handlers are a good way to replace the PHP default error-handling system. Custom error handlers can set up processing error messages in any way, including how information is displayed.

In the PHP function, the Set_error_handler () function is the complete function. When an error occurs, this function is invoked automatically, and then gives 4 parameters: the error code, the error message, the name of the script where the error occurred, and the line where the error occurred, and this function is responsible for error management.

Table E gives a simple example:

Table E

Define Custom Handler

Set_error_handler (' MyHandler ');

Custom handler Code

function MyHandler ($code, $msg, $file, $line) {

echo "Just so you know, something went wrong in line $line of your script $file. The system says that error code is $code, and the reason for the error is: $msg. Sorry about this! ";

}

Generate a Notice

Echo $undefVar;

?>

When you run this script, the following message appears:

Just so your know, something went wrong at line one of your/dev/error1.php. The system says that error code is 8, and the reason for the error was:undefined Variable:undefvar. Sorry about this!

At this point, the default error handler for PHP is replaced by the user-defined MyHandler () function, $undefVar variable is activated, PHP notifies the information that the variable is undefined, the information is generated at runtime, and then passed to the MyHandler () function. The address at which the error occurred is also passed to this function. The MyHandler () function then outputs friendly information to explain the error.

Note: Errors and fatal errors are important and they bypass the custom error handler and are displayed in the default error handling mechanism of PHP. Displaying this information can be controlled using the standard error_reporting () function discussed earlier.

Example 1: Dynamic error page and e-mail alert

Table F gives another example where an error occurs when an HTML error page is generated dynamically and is reported to the Web administrator via e-mail.

Table F

Define Custom Handler

Set_error_handler (' MyHandler ');

Custom handler Code

function MyHandler ($code, $msg, $file, $line, $context) {

Print error page

echo "";

echo "

error!

";

echo "";

echo "An error occurred while processing your request. Please visit our home page and try again. ";

echo "";

echo "";

Email error to admin

$body = "$msg at $file ($line), timed at". Date ("D-m-y h:i:s", Mktime ());

$body. = "\ n \ nthe". Print_r ($context, TRUE);

Mail ("Webmaster@domain.dom", "Web site Error", $body);

Halt execution of script

Die ();

}

Generate a Notice

Echo $undefVar;

?>

Here, the custom error processor dynamically generates an HTML error page when it encounters an error. This error message can also be captured by the e-mail message and sent to the administrator via the PHP built-in mail () function.

A new parameter $context for the MyHandler () function appears here. This is the fifth parameter of the MyHandler () function, which is optional. It contains a snapshot of the state of the current variable. Includes contextual information that is useful to administrators and helps reduce debugging time.

Example 2: Custom error log

Table G gives another example of how a custom error processor can enter a detailed error message into a file.

Table g

Define Custom Handler

Set_error_handler (' MyHandler ');

Custom handler Code

function MyHandler ($code, $msg, $file, $line) {

Print error page

echo "";

echo "

error!

";

echo "";

echo "An error occurred while processing your request. Please visit our home page and try again. ";

echo "";

echo "";

Log error to file, with context

$logData = Date ("D-m-y h:i:s", Mktime ()). ", $code, $msg, $line, $file \ n";

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 enters the error data into the file for the benefit of the administrator to view. The data is stored in CSV format and has simple data analysis and reporting. Note that in this and previous instances, the Die () function is called at the end of the error-handling code to ensure that the script is no longer running.

As the example above shows, custom error handlers allow you to handle PHP script errors in a friendly way. And be creative, but remember that any increase in flexibility is accompanied by an increase in spending 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.