PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 15 ■ AN INTRODUCTION TO PEAR AND PYRUS

Handling PEAR Errors


Many, if not most, official PEAR packages use the standard PEAR error class PEAR_Error. This is often
returned in place of the expected value if something goes wrong in an operation. This behavior should
be documented, and you can test return values using the static PEAR::isError() method.


$this->rootObj = @$conf->parseConfig($filename, $type);
if ( PEAR::isError( $this->rootObj ) ) {
print "message: ". $this->rootObj->getMessage() ."\n";
print "code: ". $this->rootObj->getCode() ."\n\n";
print "Backtrace:\n";


foreach ( $this->rootObj->getBacktrace() as $caller ) {
print $caller['class'].$caller['type'];
print $caller['function']."() ";
print "line ".$caller['line']."\n";
}
die;
}


Here, I test the return value from Config::parseConfig().

PEAR::isError( $this->rootObj )


is the functional equivalent of


$this->rootObj instanceof PEAR_Error


So within my conditional block, I know that $this->rootObj is a PEAR_Error rather than a
Config_Container object.
Once I am sure I have a PEAR_Error object, I can interrogate it for more information about the error.
In my example, I have three of the most useful methods: getMessage() returns a message that describes
the error; getCode() returns an integer corresponding to the error type (this is an arbitrary number that
the package author will have declared as a constant and, we hope, documented); and finally,
getBacktrace() returns an array of the methods and classes that lead to the error. This enables us to
work our way back through our script’s operation and locate the root cause of the error. As you can see,
getBacktrace() is itself an array, which describes each method or function that led to the error. The
elements are described in Table 15–1.


Table 15–1. Fields Provided by PEAR_Error::getBacktrace()


Field Description

file Full path to PHP file

args The arguments passed to the method or function

class The name of the class (if in class context)

function The name of the function or method

type If in class context, the nature of the method call (:: or ->)

line The line number
Free download pdf