Wednesday, April 14, 2010

Exception Handling

In PHP, we will use exceptions to change the normal flow of a script if a specified error occurs.



Basic Use of Exceptions

In the example below, when an exception is thrown, it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message. Now, I will let you try to throw an exception without catching it and see what kind of error that you will get:


(click image to view)

############################################################
The Output:

Fatal error: Uncaught exception 'Exception'
with message 'Value must be 5 or below' in C:\webfolder\index.php:6
Stack trace: #0 C:\webfolder\index.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\index.php on line 6
############################################################

To avoid the error from the example above, we need to create the proper code to handle an exception. Proper exception code should include:

  • Try - A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".
  • Throw - This is how you trigger an exception. Each "throw" must have at least one "catch".
  • Catch - A "catch" block retrieves an exception and creates an object containing the exception information.

(click image to view)

############################################################
The Output:

Message: Value must be 5 or below
############################################################

The code above throws an exception and catches it:
  1. The checkNum() function is created. It checks if a number is greater than 10. If it is, an exception is thrown.
  2. The checkNum() function is called in a "try" block.
  3. The exception within the checkNum() function is thrown.
  4. The "catch" block retrives the exception and creates an object ($e) containing the exception information.
  5. The error message from the exception is echoed by calling $e->getMessage() from the exception object.


Creating a Custom Exception Class


(click image to view)

The code above throws an exception and catches it with a custom exception class:
  1. The customException() class is created as an extension of the old exception class. This way it inherits all methods and properties from the old exception class.
  2. The errorMessage() function is created. This function returns an error message if an e-mail address is invalid.
  3. The $email variable is set to a string that is not a valid e-mail address.
  4. The "try" block is executed and an exception is thrown since the e-mail address is invalid.
  5. The "catch" block catches the exception and displays the error message.


Multiple Exception

It is possible for a script to use multiple exceptions to check for multiple conditions. It is possible to use several if..else blocks, a switch, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:


(click image to view)

(click image to view)

Thursday, April 8, 2010

Error Handling

die() Function

The example below shows a simple script that opens a text file:


(click image to view)

If the "file.txt" file does not exist, you might get an error like this:


(click image to view)

To avoid that the user gets an error message like the above, we test if the file exist before we try to access it:


(click image to view)



Custom Error Handler

It is quite simple to create a custom error handler, just by creating a function that can be called when an error occurs, and the function must be able to handle at least 2 parameters (error level & error message). The function also can accept up to 5 parameters. Please look at the description below:

Syntax:



(click image to view)



Error Report Level


(click image to view)

Let we try to create a function to handle errors:


(click image to view)

When the function above is triggered, it gets the error level and an error message. It then outputs the error level and message, and then it will terminates the script.



Set Error Handler


(click image to view)

Now, let we try testing the error handler by trying to output variable that does not exist:


(click image to view)

############################################################
The Output:

Error:
[8] Undefined variable: var
############################################################



Trigger an Error

You can trigger an error when users input the illegal data. In PHP, we will use the trigger_error() function:


(click image to view)

And the output should be something like this:

############################################################
Notice: Value must be 5 or below
in C:\webfolder\index.php on line 7
############################################################

There are several possible error types:
  • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halte.
  • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halte.
  • E_USER_NOTICE - Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normall.
The example below shows an E_USER_WARNING occurs if the var variable is bigger than 5. If an E_USER_WARNING occurs we will use our custom error handler and end the script:


(click image to view)

And the output should be something like this:

############################################################
Error: [512] Value must be 5 or below
Ending Script
############################################################



Error Logging

You maybe need to send error log to the servers logging system or remote destination, but it depend on how the error_log configuration is set in the php.ini file. In this case, it is the best way if you try to send the error log to yourself to get notified of specific errors. Lets see the code below for example:


(click image to view)

The output should be something like this:

############################################################
Error: [512] Value must be 5 or below
Administrator has been notified
############################################################

And somebody (in this case: yourself) will received mail from the code above looks like this:

############################################################
Error: [512] Value must be 5 or below
############################################################

Secure E-mail

For your information, the e-mail form can be secured from any kinds of e-mail injections by validating the user input. See the example below:


(click image to view)

(click image to view)

We actually use the PHP filter in the code above to validate user input:
  • The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string.
  • The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address.