CHAPTER 7 – PEAR ERRORS

PEAR has its own error-reporting mechanism based around the principle of errors as types, and the ability to pass around errors as values. Many extras were built around this principle, to the point where PEAR errors almost func- tion like a poor man's (in this case, PHP 4 users') exception. Where PHP's built-in error mechanism typically displays a message and a function returns false, a function returning a PEAR error gives an object back that is an instance of PEAR_Error or a subclass: <?php require_once 'DB.php'; $dbh = DB::connect('mysql://test@localhost/test'); if (PEAR::isError($dbh)) { die("DB::connect failed (" . $dbh->getMessage() . ")n"); } print "DB::connect ok!n"; ?> In this introductory example, we try connecting to a MySQL database through PEAR DB. If the connection fails, DB::connect returns a PEAR error. The PEAR::isError() static method returns a boolean that tells whether a value is a PEAR error. If the return value from DB::connect is a PEAR error, the connection attempt has failed. In this case, we call getMethod() in the error object to retrieve the error message, print it, and abort. This is a simple example of how PEAR's error handling works. There are many ways of customizing it that we will look at later. First, we examine the different ways of raising and catching PEAR errors, and get an overview of the PEAR_Error class.

Post Comment
Login to post comments