Re: PEAR: error handling in classes

From: Date: Fri, 15 Mar 2002 14:48:10 +0000
Subject: Re: PEAR: error handling in classes
References: 1  Groups: php.pear.general 
Request: Send a blank email to pear-general+get-968@lists.php.net to get a copy of this message
[CC to pear-general as it could help others too] Ondrej Jombik wrote: > > Maxim, 23:00:22 > 14. marec 2002 (stvrtok) > Greets. > > I have two simple and fast question: > > I'm creating PEAR compliant class which uses PEAR's DB class for > database access. And my question is how to work with errors. Should I check > return value of each operation if it is not PEAR Error object. Than if yes, > should I return than object from my class? Is this PEAR compliant? If your class has a function error handler you could trigger the DB errors through it. For ex: class Foo { function connect() { $this->db = DB::connect(..); // Tell PEAR DB to use your class error hanlding mechanism $this->db->setErrorHandling(PEAR_ERROR_CALLBACK, array(&$this, 'raiseError')); } function raiseError($mixed) { if (DB::isError($mixed)) { die("Error: " . $obj->getMessage()); } } } Well, I haven't really tested that but should work :-) If you don't have in your class an error handler just check each DB operation that could return an error object in case of fail and return it as a error string or false. > And what when I expect error? For example, I make query that may > fails. If someone has sets PEAR error handler, it will cause its call. How > to avoid from this? You have two ways for doing that: 1) Don't use the error of the actual error handler for errors with a certain code (the error you expect): $db->expectError(DB_ERROR_ALREADY_EXISTS); $res = $db->query("INSERT INTO .."); $db->popExpect(); 2) Temporary change the actual error handler: $db->pushErrorHandling(PEAR_ERROR_RETURN); $res = $db->query("INSERT INTO .."); $db->popErrorHandling(); To rest of the code for both cases could be: if (DB::isError($res) && $res->getCode() == DB_ERROR_ALREADY_EXISTS) { // the expected error } Hope it helps, Tomas V.V.Cox

« previous php.pear.general (#968) next »