note 103423 deleted from class.pdoexception by danbrown
| From: | danbrown@php.net | Date: | Tue, 12 Apr 2011 14:33:12 +0000 |
| Subject: | note 103423 deleted from class.pdoexception by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-178773@lists.php.net to get a copy of this message | ||
Note Submitter: Dormilich at netscape dot net
----
An extended Exception similar to the one from samuelelliot+php dot net at gmail dot com, but the
SQLSTATE is saved in its own property.
<?php
class XtPDOException extends PDOException
{
protected $sqlstate = "";
public function __construct(PDOException $e)
{
parent::__construct($e->getMessage(), $e->getCode(), $e);
// check for an SQLSTATE
$hasSQLState = (false !== strpos($e->getMessage(), "SQLSTATE["));
// set sqlstate property
if ($hasSQLState)
{
$re = '#SQLSTATE\[(\w+)\]#';
if (preg_match($re, $e->getMessage(), $matches))
{
$this->sqlstate = $matches[1];
}
}
// set message from errorInfo propery
if ($e->errorInfo)
{
$this->message = $e->errorInfo[2];
}
// or try cutting it from the original message
elseif ($hasSQLState)
{
$re = '#SQLSTATE\[\w+\](?: \[\w+\]|:) (.*)#';
if (preg_match($re, $e->getMessage(), $matches))
{
$this->message = $matches[1];
}
}
}
public function getSQLState()
{
return $this->sqlstate;
}
}
?>
usage example:
<?php
try
{
$pdo = new PDO($dns, $username, $password, $options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query('bla bla blubb');
// ...
}
catch (PDOException $e)
{
throw new XtPDOException($e);
}
?>
note: when youâre using the XDebug extension, you have a ready-to-use HTML output table in
Exception->xdebug_message.