#native_company# #native_desc#

Building an Error-Handling Mechanism Page 2

By PHP Builder Staff
on September 9, 2009

These error report levels are the different types of error the user-defined error handler can be used for:
E_WARNING(value 2): Non-fatal run-time errors. Execution of the script is not halted

E_NOTICE(value 8): Run-time notices. The script found something that might be an error, but could also happen when running a script normally

E_USER_ERROR(value 256): Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()

E_USER_WARNING(value 512): Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()

E_USER_NOTICE(value 1024): User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()

E_RECOVERABLE_ERROR(value 4096): Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())

E_ALL(value 8191): All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)
Now lets create a function to handle errors:

function customError($errno, $errstr)

echo "Error: [$errno] $errstr";
echo "Ending Script";



The code above is a simple error handling function. When it
is triggered, it gets the error level and an error message.
It then outputs the error level and message and terminates
the script. Now that we have created an error handling
function we need to decide when it should be triggered.
The default error handler for PHP is the built in error
handler. We are going to make the function above the default
error handler for the duration of the script. It is possible
to change the error handler to apply for only some errors,
that way the script can handle different errors in different
ways. However, in this example we are going to use our
custom error handler for all errors:

Since we want our custom function to handle all errors, the
set_error_handler() only needed one parameter,
a second parameter could be added to specify an error level.
Testing the error handler by trying to output variable that does not exist:

//error handler function 
function customError($errno, $errstr) 
    echo "Error: [$errno] $errstr"; 

//set error handler 

//trigger error 
The output of the code above should be something like this:
Custom error: [8] Undefined variable: example
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.
In this example an error occurs if the “example” variable is larger than 1:


if ($example > 1) 
    trigger_error("Value must be 1 or below"); 
The output of the code above should be something like

Notice: Value must be 1 or below

in C:directoryfile.php on line 6