Hindi Songs

Search About PHP!!!

Wednesday, July 8, 2009

Trigger an Error

In a script where users can input data it is useful to trigger errors when an illegal input occurs. In PHP, this is done by the trigger_error() function.

Example

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

< ?php
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below");
}
? >

The output of the code above should be something like this:

Notice: Value must be 1 or below
in C:\webfolder\test.php on line 6

An error can be triggered anywhere you wish in a script, and by adding a second parameter, you can specify what error level is triggered.

Possible error types:

  • E_USER_ERROR - Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
  • E_USER_WARNING - Non-fatal user-generated run-time warning. Execution of the script is not halted
  • 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 normally

Example

In this example an E_USER_WARNING occurs if the "test" variable is bigger than "1". If an E_USER_WARNING occurs we will use our custom error handler and end the script:

< ?php
//error handler function
function customError($errno, $errstr)
{
echo "Error: [$errno] $errstr
";
echo "Ending Script";
die();
}

//set error handler
set_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 code above should be something like this:

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

Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.