#native_company# #native_desc#
#native_cta#

Building an Error-Handling Mechanism Page 3

By PHP Builder Staff
on September 9, 2009

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.
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

In this example an E_USER_WARNING occurs if the “example” variable is greater 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

$example = 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.
By default, PHP sends an error log to the servers logging
system or a file, depending on how the error_log
configuration is set in the php.ini file. By using the
error_log() function you can send error logs to
a specified file or a remote destination.
Sending errors messages to yourself by e-mail can be a
good way of getting notified of specific errors.
In the example below we will send an e-mail with an error
message and end the script, if a specific error occurs:

<?php 
//error handler function 
function customError($errno, $errstr) 
{ 
    echo "Error: [$errno] $errstr"; 
     echo "Webmaster has been notified"; 
    error_log("Error: [$errno] $errstr",1, 
    "[email protected]","From: [email protected]"); 
} 

//set error handler 
set_error_handler("customError",E_USER_WARNING); 

//trigger error 
$example=2; 
if($example > 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

Webmaster has been notified

And the mail received from the code above looks like this:

ERROR: [512] VALUE MUST BE 1 OR BELOW
Conclusion
Something best remembered is that users do not want to see
your error messages. They are there for the content.
Something important to do is to show them a meaningful
notice should that content not be available to them. Above I
have shown very technical error reporting, but I think you
can find your own balance between what you need to know and
what the user needs to see.
Until next time.
Marc Steven Plotz