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

PEAR::expectError() int expectError(mixed expect) This method is a more specific approach to the same problem that pushErrorHandling() tries to solve: making an exception (in the traditional sense of the word) for errors we want to handle differently. The expectError() approach is to look for one or more specified error codes or error messages, and force the error mode to PEAR_ERROR_RETURN for matching errors, thus disabling any handlers. If the expect parameter is an integer, it is compared to the error code of the raised error. If they match, any specified error handler is disabled, and the error object is silently returned. If expect is a string, the same thing is done with the error message, and as a special case the string "*" matches every error message. Thus, expectEr- ror('*') has the same effect as pushErrorHandling(PEAR_ERROR_RETURN). Finally, if expect is an array, the previous rules are applied to each ele- ment, and if one matches, the error object is just silently returned. The return value is the new depth of the object's expect stack (or the glo- bal expect stack if called statically). Let's repeat the last example using expectError() instead of pushError Handling(): <?php require_once 'PEAR.php'; require_once 'DB.php'; PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aborting: %sn"); $dbh = DB::connect('mysql://test@localhost/test'); // temporarily disable the default handler for this error code: $dbh->expectError(DB_ERROR_ALREADY_EXISTS); $res = $dbh->query("INSERT INTO mytable VALUES(1, 2, 3)"); // back to PEAR_ERROR_DIE again: $dbh->popExpect(); if (PEAR::isError($res) && $res->getCode() == DB_ERROR_ALREADY_EXISTS) { print "Duplicate record!n"; } ?> In this example, we use the per-object default error handling in the $dbh object instead of the global default handler to implement our graceful dupli- cate handling. The main difference from the pushErrorHandling() approach is that we don't have to re-throw/raise the error because our "duplicate handling code" is called only if a duplicate error occurred, and not if any error occurred as would have been the case with pushErrorHandling().

Post Comment
Login to post comments