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'@'example.com' (using password: YES)"
Using my extended exception class provides:
CODE: "28000"
Message: "Access denied for user 'user'@'example.com' (using password: YES)"
<?php
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:
<?php
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.
<?php
echo $err->getCode(); echo $err->getMessage(); ?>
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.