Home arrow PHP arrow Page 3 - PHP Application Development Part Two

Error Handling - PHP

Building on what we learned in part one, this article discusses data storage, system configuration, error handling and logging. Read on to find out how practicing the proper use of these concepts can simplify application maintenance and testing, and accelerate system debugging.

  1. PHP Application Development Part Two
  2. Storing Dynamic Data
  3. Error Handling
  4. Event Logging
By: David Fells
Rating: starstarstarstarstar / 36
March 08, 2005

print this article



Error handling is the next subject for discussion. Error handling is a topic that could (and does) fill an entire book, but for our purposes we only need to understand the fundamentals. Error handling should be “graceful” in any system – meaning that the application should know how to detect its own errors and handle them in some appropriate manner with minimal interruption for end users. In PHP, error handling is something that developers tend to overcomplicate. There is a tendency to use elaborate error handling classes that store far more information than is needed and not the information that is really needed. The following example demonstrates a simple error class.

class Error
 var $number;
 var $string;
 var $file;
 var $line;

 function setError($number, $string, $file, $line)
  $this->number = $number;
  $this->string = $string;
  $this->file = $file;
  $this->line = $line;


function showError()
 print ‘Error (‘.$this->code.’): ‘.$this->message.”<br />
”.$this->file.’ (‘.$this->line.’)<br />’;

This very simple class takes in the error data via the “setError” function and spits the data back out via “showError.” The two methods are chained together. While this class is not especially useful for handling errors gracefully, it is the foundation for capturing the errors after attempts at a graceful recovery have failed and for acting upon the information provided by the error. Task-specific error handling is best left for the actual scripts or classes performing the task.

Implementing this class as our error handler in PHP is simple. See the following example.

$errorHandler = &new Error();
set_error_handler(array(&$errorHandler, ‘setError’));

This will send any error in the script to “$errorHandler”. Consider the following sample, where the script will attempt to recover from a failed database connection by iterating over a set of possible databases. Data from the configuration file that would be used in this situation is inserted into the file directly. Assume that “class.error.php” contains our error class and is available in the default include path.

$settings[‘db’][0][‘user’] = ‘someuser’;
$settings[‘db’][0][‘pass’] = ‘password’;
$settings[‘db’][0][‘host’] = ‘’;
$settings[‘db’][0][‘name’] = ‘MyApp’;

$settings[‘db’][1][‘user’] = ‘root’;
$settings[‘db’][1][‘pass’] = ‘password’;
$settings[‘db’][1][‘host’] = ‘’;
$settings[‘db’][1][‘name’] = ‘MyApp’;

$settings[‘db’][2][‘user’] = ‘root’;
$settings[‘db’][2][‘pass’] = ‘’;
$settings[‘db’][2][‘host’] = ‘localhost’;
$settings[‘db’][2][‘name’] = ‘MyApp’;

$errorHandler = &new Error();
set_error_handler(array(&$errorHandler, ‘setError’));

$dbh = false;
$try = 0;
 $dbh = @mysql_connect($settings[‘db’][$try][‘host’],
} while (($dbh === false) && ($try < count($settings[‘db’])));

if ($dbh === false)
 trigger_error(‘Unable to connect to database.’, E_USER_ERROR);

In this example we have two available hosts that attempt to establish a database connection with “mysql_connect” one host at a time until a connection is established. This is a type of error recovery – our application is provided with alternate possible databases to try connecting to before failing. If no connection can be made, we will pass a fatal error notice to our error handler.

Typically just a warning would be generated from a failed MySQL connection, but since our example application is dependent on one, the script needs to halt. A more elaborate configuration could involve the error handler being configured with objects to delegate errors to, in this case perhaps some top level object that handles stopping a script and presenting a user with the appropriate message. We could also extend our Error class and delegate certain types of errors or errors that match certain keywords to the appropriate subclass.

In PHP 5, error handling is even more powerful with exceptions and try/catch structures, allowing developers to specialize error handling on a per-object or even per-task basis, maximizing the usefulness of the data provided by the exceptions. Since this article is meant to be general and the example above also works in PHP 5, we will not have an exceptions example, though the principles are still the same.

Error handling is a pretty broad subject and the example above only chips the iceberg. Ultimately, error handling becomes very narrow in the context of a particular task, and in those cases you as a developer must use your experience and your problem solving skills to determine what options are available for handling the error, and how to handle it as succinctly and effectively as possible.

One of the most important uses of error handling in a live application is to capture real errors generated by real use of the system. This allows developers to work with live data, often in ways they did not predict during initial testing. There is a problem, though; how do developers know what error data is going through their application? One word: logging.

>>> More PHP Articles          >>> More By David Fells

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: