News:

MyKidsDiary.in :: Capture your kids magical moment and create your Online Private Diary for your kids

Main Menu

Trigger an Error

Started by sajiv, Aug 23, 2008, 04:55 PM

Previous topic - Next topic

sajiv


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":

Code:

<?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:
Code:
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.

[blink]Possible error types:[/blink]
*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:

Code:
<?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:
Code:
Error: [512] Value must be 1 or below
Ending Script
[blink]Now that we have learned to create our own errors and how to trigger them, lets take a look at error logging.[/blink]

:acumen