note 95812 added to class.pdoexception

From: Date: Sat, 23 Jan 2010 02:13:21 +0000
Subject: note 95812 added to class.pdoexception
Groups: php.notes 
Request: Send a blank email to php-notes+get-165223@lists.php.net to get a copy of this message
Here is something interesting regarding a PDOException and it involves some of the annoyances that can be associated with PHP's dynamic nature. PDOException extends from RuntimeException, which in return extends from Exception. As such, it has access to the $code Protected Class Variable, which represents the Exception's code as an Integer (duh!) and can be accessed externally using the Exception::getCode Method. Here is the interesting part. PDOException actually redefines $code as a String and not an Integer because for its case, $code actually contains the Exception's SQL State, which is composed of characters and numbers. It is actually documented in the manual that $code is a String and not an Integer but it might not be immedietley clear because it is hidden by the fact that PDOException::getCode is documented to return an Integer and not a String! Some developers like to catch a PDOException and rethrow it as a different Exception if they wrap their database calls in an external library. For example, consider the following code: <?php try { $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException. } catch( PDOException $Exception ) { // PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A // String. throw new MyDatabaseException( $Exception->getMessage( ) , $Exception->getCode( ) ); } ?> Be careful in that you have to typecast the value returned by PDOException::getCode to an Integer BEFORE you pass it as an Argument to your Exception's Constructor. The following will work: <?php try { $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException. } catch( PDOException $Exception ) { // Note The Typecast To An Integer! throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) ); } ?> Hope this will save some developers some frustrating hours from an otherwise enjoyable job :) Good Luck, ---- Server IP: 69.147.83.197 Probable Submitter: 217.54.224.164 ---- Manual Page -- http://www.php.net/manual/en/class.pdoexception.php Edit -- https://master.php.net/note/edit/95812 Del: integrated -- https://master.php.net/note/delete/95812/integrated Del: useless -- https://master.php.net/note/delete/95812/useless Del: bad code -- https://master.php.net/note/delete/95812/bad+code Del: spam -- https://master.php.net/note/delete/95812/spam Del: non-english -- https://master.php.net/note/delete/95812/non-english Del: in docs -- https://master.php.net/note/delete/95812/in+docs Del: other reasons-- https://master.php.net/note/delete/95812 Reject -- https://master.php.net/note/reject/95812 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#165223) next »