Customization of the PHP exception handler

Source: Internet
Author: User
Tags php error php exception handling
You will inevitably encounter some abnormal errors in programming. Reasonable handling of exceptions, so that they are not perceived by the user, is what we want to do. Share a custom exception handler method today.

Create a custom error handler

Creating a custom error handler is straightforward. We have simply created a special function that can be called when an error occurs in PHP.

The function must be capable of handling at least two parameters (Error level and error message), but can accept up to five parameters (optional: File, Line-number, and error context):

Grammar

Error_function (Error_level,error_message,

Error_file,error_line,error_context)

Parameter description

Error_level

Necessary. Specifies the error reporting level for user-defined errors. Must be a number of values.

See the table below: Error reporting levels.

Error_message required. Specifies error messages for user-defined errors.

Error_file is optional. Specifies the file name in which the error occurred.

Error_line is optional. Specifies the line number where the error occurred.

Error_context is optional. Specifies an array that contains each variable that was used when the error occurred and their value.

Error Reporting level

These error reporting levels are different types of errors that the error handler is designed to handle:

Value constant Description

2 e_warning non-fatal run-time error. Script execution is not paused.

8 E_notice

Run-time notice.

The script discovers that an error may have occurred, but it may also occur when the script is running correctly.

The e_user_error fatal user-generated error. This is similar to the e_error that programmers use to set the PHP function Trigger_error ().

E_user_warning a non-fatal user-generated warning. This is similar to the e_warning that programmers use to set the PHP function Trigger_error ().

1024x768 E_user_notice user-generated notifications. This is similar to the e_notice that programmers use to set the PHP function Trigger_error ().

4096 E_recoverable_error A fatal error that can be captured. Similar to E_error, but can be captured by user-defined handlers. (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)

Now, let's create a function that handles the error:

function Customerror ($errno, $errstr) {echo "Error: [$errno] $errstr"; echo "ending Script";d ie ();}

The above code is a simple error-handling function. When it is triggered, it gets the error level and error message. It then outputs the error level and message, and terminates the script.

Now that we have created an error handler, we need to determine when the function is fired.

Set Error Handler

The default error handler for PHP is the built-in error handler. We are going to transform the above function into the default error handler during the script run.

You can modify the error handler so that it applies only to certain errors, so that the script can handle different errors in different ways. However, in this case, we intend to use our custom error handlers for all errors:

Set_error_handler ("Customerror");

Since we want our custom function to handle all errors, Set_error_handler () requires only one parameter and can add a second parameter to specify the error level.

Instance

Test the error handler by trying to output a variable that does not exist:

<?php//error handler Functionfunction customerror ($errno, $errstr) {echo "error: [$errno] $errstr";} Set error Handlerset_error_handler ("Customerror");//trigger Errorecho ($test);? >

The output of the above code should look like this:

Error: [8] Undefined Variable:test

Trigger Error

The location of the user input data in the script is useful for triggering errors when the user's input is not valid. In PHP, this task is done by Trigger_error ().

Example

In this example, if the "test" variable is greater than "1", an error occurs:

<?php

$test = 2;

if ($test >1)

{

Trigger_error ("Value must be 1 or below");

}

?>

The output of the above code should look like this:

Notice:value must be 1 or below

In C:\webfolder\test.php on line 6

You can trigger an error anywhere in the script, and by adding a second parameter, you can specify the level of error that is triggered.

Possible types of errors:

E_user_error-Fatal user generated run-time error. The error cannot be recovered. The execution of the script was interrupted.

E_user_warning-A non-fatal user-generated run-time warning. Script execution is not interrupted.

E_user_notice-Default. User-generated Run-time notifications. The script found a possible error, or it might occur when the script is running normally.

Example

In this example, if the "test" variable is greater than "1", a e_user_warning error occurs. If e_user_warning occurs, we will use our custom error handler and end the script:

<?php//error handler Functionfunction customerror ($errno, $errstr) {echo "error: [$errno] $errstr"; echo "ending Script ";d ie ();} Set error Handlerset_error_handler ("Customerror", e_user_warning);//trigger error$test=2;if ($test >1) {Trigger_ Error ("Value must be 1 or below", e_user_warning);}? >

The output of the above code should look like this:

Error: [+] Value must be 1 or below

Ending Script

Now that we've learned how to create our own error, and how to trigger them, let's look at the error record.

Error logging

By default, PHP sends error records to the server's error logging system or file, based on the Error_log configuration in php.ini. By using the Error_log () function, you can send an error record to a specified file or remote destination.

Sending an error message to yourself via e-mail is a good way to get notification of a specified error.

Send error message via e-mail

In the following example, if a specific error occurs, we will send an e-mail with an error message and end the script:

<?php//error handler Functionfunction customerror ($errno, $errstr) {echo "error: [$errno] $errstr"; echo "Webmaster has been notified "; Error_log (" Error: [$errno] $errstr ", 1," someone@example.com "," from:webmaster@example.com ");} Set error Handlerset_error_handler ("Customerror", e_user_warning);//trigger error$test=2;if ($test >1) {Trigger_ Error ("Value must be 1 or below", e_user_warning);}? >

The output of the above code should look like this:

Error: [+] Value must be 1 or below

Webmaster has been notified

Messages received from the above code are similar to this:

Error: [+] Value must be 1 or below

This method is not suitable for all errors. General errors should be logged on the server by using the default PHP record system.

Related recommendations:

PHP Exception Handling Exception class

PHP error handling mechanism

php Error Level setting method

Related Article

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.