Re: DB Exceptions - Sample Code

From: Date: Thu, 08 Jul 2004 22:21:17 +0000
Subject: Re: DB Exceptions - Sample Code
References: 1  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-31768@lists.php.net to get a copy of this message
Arthur Hundiak wrote:
I took the latest PEAR DB code and tweaked it to run under PHP5 E_STRICT. I also tweaked PEAR.php as well. I then added the ability to set an "error mode" which causes DB to throw exceptions instead of returning errors. The application can chose between using error objects or exceptions. I then added a couple of very simple test files which show some of the differences between the modes. The code is available from: http://www.cerad.org/pear/pear5a.tgz I think having some running code to look at might help in this debate. IMHO, allowing the application to chose how unusual conditions are dealt with might be the way to go.
Arthur, Thanks for the code. I'd like to correct the example for duplicate user insertion, based on my explanation of Exception Types in the wiki document: http://wiki.ciaweb.net/yawiki/?area=PEAR_Dev&page=RfcExceptionUse#toc6 In your example, you catch the generic PEAR_Exception, and then try to check if it is a case of duplicate insertion by using the error code. Error codes are in fact made obsolete by a proper Exception class hierarchy. Your code looks like this:
    /* Catch duplicate user with exceptions */
    try {
        $db->query("INSERT INTO users VALUES(3,'Art');");
    }
    catch (PEAR_Exception $ex) {
        $code = $ex->getCode();
        if ($code == DB_ERROR_ALREADY_EXISTS) {
            // Deal with duplicate entry
            echo "Duplicate user name (exception)\n";
        }
        else {
            throw $ex;
        }
    }
Whereas with correct design of DB package exceptions, it would look something like this:
    /* Catch duplicate user with exceptions */
    try {
        $db->query("INSERT INTO users VALUES(3,'Art');");
    }
    catch (DB_AlreadyExistsException $ex) {
        echo "Duplicate user name (exception)\n";
    }
And this isn't a lot more convoluted or than regular return code handling. Cheers, Sérgio Carvalho

Attachment: [application/pgp-signature] OpenPGP digital signature signature.asc
« previous php.pear.dev (#31768) next »