HomePHP Page 4 - Error Handling in PHP: Coding Defensively
The PEAR way: looking at the PEAR_Error object - PHP
As with any programming language, when you code in PHP, it helps immensely if you set up your applications to handle errors gracefully. This article explores some of the most common error checking methods available in PHP, and provides hands-on examples that use different error handling methods.
In PHP 4 object-oriented scenarios, one of the most popular approaches for handling errors is the PEAR_Error object. While not all developers feel comfortable working with PEAR packages, admittedly it’s a very strong framework that can be used in numerous applications. Specifically, the PEAR_Error object is extremely useful for handling errors, and certainly provides a lot of information that you might need. Let’s have a look at its methods:
- PEAR::getMessage(): returns the error message. - PEAR::getType(): returns the PEAR_Error subtype. - PEAR::getUserInfo(): returns additional information on the error and the context where it took place - PEAR::getCode(): return the error code. Eventually, this method might return no values.
Having described the corresponding object methods, the next step will consist of modifying the sample class, so it can return a PEAR_Error object, instead of using the “trigger_error()” function:
// include PEAR library require_once("PEAR.php");
class FileReader{ var $file; var $fileDir='fileDir/'; function FileReader($file){ if(!file_exists("{$this->fileDir}{$file}.php")){ return PEAR::RaiseError('File '.$file. ' not found'); } $this->file=$file; } function getContent(){ if(!$content=file_get_contents("{$this->fileDir}{$this->file}.php")){ return PEAR::RaiseError('Unable to read file contents'); } return $content; } }
As you can see, now the above class returns a PEAR_Error object when things go wrong. Given the existence of this object, I’m able to call one of its methods, as follows:
The above example demonstrates how to check for the existence of an error object, and accordingly call its “getMessage()” method. Evidently, this method provides much more flexibility and allows you to obtain specific information on both the nature of the error and the context in which it took place.
Of course, this is only a introductory example, so if you feel curious about PEAR, visit its site (http://pear.php.net/) and browse the numerous packages available for downloading.
Having scratched the surface of PEAR_Error objects, let’s leap forward and analyze the last method for handling program failures, in this case by utilizing Boolean flags.