CHAPTER 7 – Graceful Handling – PEAR::pushErrorHandling()

bool PEAR::pushErrorHandling(int mode, [mixed options]) This method pushes another error-handling mode on top of the default han- dler stack. This error mode will be used until popErrorHandling() is called. You may call this method statically or in an object context. As with other methods that have this duality, global defaults are used when called statically, and the object defaults when in an object context. Here is an extended version of the first example. After connecting, we insert some data into a table, and handle duplicate keys gracefully: <?php require_once 'PEAR.php'; require_once 'DB.php'; PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aborting: %sn"); $dbh = DB::connect('mysql://test@localhost/test'); // temporarily set the global default error handler PEAR::pushErrorHandling(PEAR_ERROR_RETURN); $res = $dbh->query("INSERT INTO mytable VALUES(1, 2, 3)"); // PEAR_ERROR_DIE is once again the active error handler PEAR::popErrorHandling(); if (PEAR::isError($res)) { // duplicate keys will return this error code in PEAR DB: if ($res->getCode() == DB_ERROR_ALREADY_EXISTS) { print "Duplicate record!n"; } else { PEAR::throwError($res); } } ?> First, we set up a default error handler that prints the error message and exits. After successfully connecting to the database (the default error handler will make the script exit if the connection fails), we push PEAR_ERROR_RETURN as the global default error mode while executing a query that may return an error. Once the query is done, we pop away the temporary error mode. If the query returned an error, we check the error code to see if it is a situation we know how to handle. If it was not, we re-throw the error, which causes the original global defaults (PEAR_ERROR_DIE) to apply.

Post Comment
Login to post comments