我正在拔这根头发。
在ZF1中,这很容易,因为它会引发一个带有完整sql错误详细信息的异常。在ZF2中,它只引发Exception''RuntimeException,它只传递错误的描述,而不是使其无法处理的数字。
问题:如何从适配器中获得完整的错误。以下是我使用的代码片段:
$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
}
有什么建议吗?
在从PHP扩展的ZF2异常中SPL异常。它们都扩展了标准的Exception接口。遵循异常手册,您可以执行以下操作:
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";
}
仅供参考,您可以为不同的异常类型实现多个捕获,如下所示:
try {
...
} catch ('RuntimeException $e) {
...
} catch ('LogicException $e) {
...
}
更新:
用于直接从'mysqli
实例获取错误数据:
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";
}
有关如何获取'mysqli
错误和警告数据的更多信息,请查看手册。