note 97908 added to class.pdoexception
| From: | samuelelliot+php dot net at gmail dot com | Date: | Sat, 15 May 2010 07:45:09 +0000 |
| Subject: | note 97908 added to class.pdoexception | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-169270@lists.php.net to get a copy of this message | ||
PDOException has two methods for retrieving information about an error. When interpreting the
PDOException I run into a problem, the error code that is provided by getCode() is meaningless. I
have come up with a method to make both the error code and message more usable.
A bad username or password would normally provide the following:
CODE : 0
Message : "SQLSTATE[28000] [1045] Access denied for user
'user'@'domain.com' (using password: YES)"
Using my extended exception class provides:
CODE: "28000"
Message: "Access denied for user 'user'@'domain.com' (using password:
YES)"
class pdoDbException extends PDOException {
public function __construct(PDOException $e) {
if(strstr($e->getMessage(), 'SQLSTATE[')) {
preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(),
$matches);
$this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
$this->message = $matches[3];
}
}
}
To walk threw the method; first the beginning of the message is checked for the SQLSTATE text. If
the text is present, message is then parsed to pull the ANSI code, the SQL specific code, and the
message. The parsed values are stored in there respective variables. The error code variable
stores the ANSI code, unless ANSI is 'HT000' (unmapped error code) then SQL specific code
is used.
Using this class is easy; when interacting with PDO use a try catch set of blocks, as follows:
try {
$pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
throw new pdoDbException($e);
}
Now you can use the normal error methods to retrieve the real error code and message.
echo $err->getCode(); // Outputs: "28000"
echo $err->getMessage(); // Outputs: "Access denied for user
'user'@'domain.com' (using password: YES)"
If you decide to use this code, be aware that the error code is a string (as apposed to PHP standard
errors which are integers) as some error codes are alphanumeric.
----
Server IP: 69.147.83.197
Probable Submitter: 72.187.57.202
----
Manual Page -- http://www.php.net/manual/en/class.pdoexception.php
Edit -- https://master.php.net/note/edit/97908
Del: integrated -- https://master.php.net/note/delete/97908/integrated
Del: useless -- https://master.php.net/note/delete/97908/useless
Del: bad code -- https://master.php.net/note/delete/97908/bad+code
Del: spam -- https://master.php.net/note/delete/97908/spam
Del: non-english -- https://master.php.net/note/delete/97908/non-english
Del: in docs -- https://master.php.net/note/delete/97908/in+docs
Del: other reasons-- https://master.php.net/note/delete/97908
Reject -- https://master.php.net/note/reject/97908
Search -- https://master.php.net/manage/user-notes.php