Reputation: 125
I'm pulling the hair on this one.
In ZF1 it was easy as it would raise an exception with full sql error details. In ZF2 it only raises Exception\RuntimeException which only passes the description of error and not the number which makes it impossible to work with.
Question: how to get the full error out of the Adapter. Here is the snippet of the code I use:
$dbAdapter = $this->_serviceManaget->get('Zend\Db\Adapter\Adapter');
try {
$result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {
//here I need to check the error number raised by MySQL during the execution
//$e object in this case only contains
//$e->message = "Duplicate entry 'blablabla' for key 319" and $e->code = 0
}
Any suggestions?
Upvotes: 3
Views: 3057
Reputation: 14491
In ZF2 Exceptions extended from PHP SPL Exceptions. They all extends standard Exception interface. Following Exception manual you can do this:
try {
$result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {
$code = $e->getCode();
$msg = $e->getMessage();
$file = $e->getFile();
$line = $e->getLine();
echo "$file:$line ERRNO:$code ERROR:$msg";
}
FYI you can implement multiple catches for different exception types like this:
try {
...
} catch (\RuntimeException $e) {
...
} catch (\LogicException $e) {
...
}
Update:
For getting error data directly from \mysqli
instance:
try {
$result = $dbAdapter->query($sql, $binds);
} catch (\Exception $e) {
$mysqli = $dbAdapter->getDriver()->getConnection()->getResource();
$file = $e->getFile();
$line = $e->getLine();
echo "$file:$line ERRNO:$mysqli->errno ERROR:$mysqli->error";
}
For more information about how to obtain \mysqli
errors and warnings data check manual.
Upvotes: 2